[llvm] [llvm] Use dyn_cast_if_present instead of dyn_cast_and_nonnull (NFC) (PR #75733)

Kazu Hirata via llvm-commits llvm-commits at lists.llvm.org
Sat Dec 16 23:38:54 PST 2023


https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/75733

Note that dyn_cast_and_nonnull has been soft-deprecated since:

  commit f156b51aecc676a9051136f6f5cb74e37dd574d1
  Author: bzcheeseman <12992886+bzcheeseman at users.noreply.github.com>
  Date:   Sat Apr 16 11:34:08 2022 -0700


>From b7c203ef24b9671c47c31a84bc11b8c845841ac5 Mon Sep 17 00:00:00 2001
From: Kazu Hirata <kazu at google.com>
Date: Sat, 16 Dec 2023 20:58:41 -0800
Subject: [PATCH] [llvm] Use dyn_cast_if_present instead of
 dyn_cast_and_nonnull (NFC)

Note that dyn_cast_and_nonnull has been soft-deprecated since:

  commit f156b51aecc676a9051136f6f5cb74e37dd574d1
  Author: bzcheeseman <12992886+bzcheeseman at users.noreply.github.com>
  Date:   Sat Apr 16 11:34:08 2022 -0700
---
 .../include/llvm/Analysis/SparsePropagation.h |  7 +--
 llvm/include/llvm/CodeGen/BasicTTIImpl.h      |  4 +-
 llvm/include/llvm/CodeGen/GlobalISel/Utils.h  |  2 +-
 llvm/include/llvm/IR/DebugInfoMetadata.h      | 20 ++++-----
 llvm/include/llvm/IR/InstrTypes.h             |  2 +-
 llvm/include/llvm/IR/Metadata.h               |  6 +--
 llvm/include/llvm/IR/PatternMatch.h           | 17 +++----
 llvm/include/llvm/IR/Statepoint.h             |  2 +-
 .../llvm/ProfileData/InstrProfReader.h        |  2 +-
 llvm/lib/Analysis/CallGraphSCCPass.cpp        |  2 +-
 llvm/lib/Analysis/ConstantFolding.cpp         | 16 +++----
 llvm/lib/Analysis/IVDescriptors.cpp           |  2 +-
 llvm/lib/Analysis/InlineCost.cpp              | 22 +++++-----
 llvm/lib/Analysis/InstructionSimplify.cpp     |  2 +-
 llvm/lib/Analysis/LazyValueInfo.cpp           |  9 ++--
 llvm/lib/Analysis/LoopAccessAnalysis.cpp      |  6 +--
 llvm/lib/Analysis/LoopCacheAnalysis.cpp       |  2 +-
 llvm/lib/Analysis/LoopInfo.cpp                |  7 +--
 .../lib/Analysis/MemoryDependenceAnalysis.cpp |  4 +-
 llvm/lib/Analysis/MemorySSA.cpp               |  4 +-
 llvm/lib/Analysis/MemorySSAUpdater.cpp        | 10 ++---
 llvm/lib/Analysis/MustExecute.cpp             |  2 +-
 llvm/lib/Analysis/PHITransAddr.cpp            |  2 +-
 llvm/lib/Analysis/ScalarEvolution.cpp         |  2 +-
 llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp  | 10 ++---
 llvm/lib/Analysis/ValueTracking.cpp           | 16 +++----
 llvm/lib/AsmParser/LLParser.cpp               |  6 +--
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp     | 31 ++++++-------
 llvm/lib/Bitcode/Reader/MetadataLoader.cpp    | 37 ++++++++--------
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp    |  4 +-
 llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp | 18 ++++----
 llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp     | 14 +++---
 llvm/lib/CodeGen/CodeGenPrepare.cpp           | 10 ++---
 .../lib/CodeGen/GlobalISel/CombinerHelper.cpp |  2 +-
 .../CodeGen/GlobalISel/LegalizerHelper.cpp    |  2 +-
 llvm/lib/CodeGen/GlobalISel/Utils.cpp         |  2 +-
 llvm/lib/CodeGen/LowerEmuTLS.cpp              |  2 +-
 llvm/lib/CodeGen/MIRParser/MIParser.cpp       |  4 +-
 llvm/lib/CodeGen/MIRParser/MIRParser.cpp      |  6 +--
 llvm/lib/CodeGen/MachineFunction.cpp          |  2 +-
 .../lib/CodeGen/SelectionDAG/SelectionDAG.cpp | 10 ++---
 .../SelectionDAG/SelectionDAGBuilder.cpp      | 15 ++++---
 .../SelectionDAG/StatepointLowering.cpp       |  2 +-
 llvm/lib/CodeGen/StackColoring.cpp            |  6 +--
 .../CodeGen/StackFrameLayoutAnalysisPass.cpp  |  2 +-
 llvm/lib/CodeGen/StackSlotColoring.cpp        |  4 +-
 llvm/lib/CodeGen/TargetLoweringBase.cpp       |  4 +-
 llvm/lib/CodeGen/WinEHPrepare.cpp             |  4 +-
 llvm/lib/DebugInfo/DWARF/DWARFContext.cpp     |  6 +--
 llvm/lib/DebugInfo/PDB/PDBContext.cpp         |  9 ++--
 .../PDB/PDBSymbolTypeFunctionSig.cpp          |  3 +-
 llvm/lib/DebugInfo/Symbolize/Symbolize.cpp    |  3 +-
 .../ExecutionEngine/Orc/ExecutionUtils.cpp    | 11 +++--
 llvm/lib/IR/AsmWriter.cpp                     | 18 ++++----
 llvm/lib/IR/AutoUpgrade.cpp                   | 16 +++----
 llvm/lib/IR/BasicBlock.cpp                    |  2 +-
 llvm/lib/IR/ConstantFold.cpp                  |  2 +-
 llvm/lib/IR/Constants.cpp                     | 20 ++++-----
 llvm/lib/IR/Core.cpp                          | 12 ++---
 llvm/lib/IR/DIBuilder.cpp                     |  4 +-
 llvm/lib/IR/DebugInfo.cpp                     | 14 +++---
 llvm/lib/IR/DebugInfoMetadata.cpp             |  2 +-
 llvm/lib/IR/LLVMContextImpl.h                 | 14 +++---
 llvm/lib/IR/Mangler.cpp                       |  3 +-
 llvm/lib/IR/Metadata.cpp                      |  6 +--
 llvm/lib/IR/Module.cpp                        | 22 +++++-----
 llvm/lib/IR/ModuleSummaryIndex.cpp            |  8 ++--
 llvm/lib/IR/ProfileSummary.cpp                | 12 ++---
 llvm/lib/IR/Type.cpp                          |  2 +-
 llvm/lib/IR/User.cpp                          |  2 +-
 llvm/lib/IR/Value.cpp                         |  7 +--
 llvm/lib/IR/Verifier.cpp                      | 44 +++++++++----------
 llvm/lib/LTO/LTO.cpp                          |  2 +-
 llvm/lib/Linker/LinkModules.cpp               |  4 +-
 llvm/lib/MC/MCObjectStreamer.cpp              |  6 +--
 llvm/lib/MC/MCParser/ELFAsmParser.cpp         |  3 +-
 llvm/lib/MC/MCParser/MasmParser.cpp           |  2 +-
 llvm/lib/MC/MachObjectWriter.cpp              |  2 +-
 llvm/lib/Object/ArchiveWriter.cpp             |  2 +-
 llvm/lib/ObjectYAML/ELFEmitter.cpp            |  6 +--
 llvm/lib/ProfileData/InstrProf.cpp            |  3 +-
 llvm/lib/Support/YAMLTraits.cpp               |  6 +--
 llvm/lib/TableGen/Error.cpp                   |  5 ++-
 llvm/lib/TableGen/Record.cpp                  | 26 +++++------
 llvm/lib/TableGen/TGParser.cpp                |  4 +-
 .../Target/AArch64/AArch64ISelLowering.cpp    | 12 ++---
 .../AArch64/AArch64MachineFunctionInfo.cpp    |  2 +-
 .../AArch64/AArch64TargetTransformInfo.cpp    | 13 +++---
 .../AArch64/AsmParser/AArch64AsmParser.cpp    |  4 +-
 .../Target/AMDGPU/AMDGPUCodeGenPrepare.cpp    |  2 +-
 llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp     | 12 ++---
 llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp      |  8 ++--
 .../Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp  |  2 +-
 .../AMDGPU/AMDGPUTargetTransformInfo.cpp      |  4 +-
 .../R600OpenCLImageTypeLoweringPass.cpp       |  2 +-
 llvm/lib/Target/ARM/ARMConstantPoolValue.cpp  |  4 +-
 .../lib/Target/ARM/ARMTargetTransformInfo.cpp |  2 +-
 .../lib/Target/ARM/AsmParser/ARMAsmParser.cpp |  4 +-
 .../ARM/MCTargetDesc/ARMELFStreamer.cpp       |  5 ++-
 .../Target/BPF/BPFAbstractMemberAccess.cpp    |  2 +-
 llvm/lib/Target/BPF/BTFDebug.cpp              |  2 +-
 .../DirectXIRPasses/PointerTypeAnalysis.cpp   |  2 +-
 .../Target/Hexagon/HexagonISelLowering.cpp    |  2 +-
 .../Hexagon/HexagonLoopIdiomRecognition.cpp   |  2 +-
 .../LoongArch/LoongArchTargetMachine.cpp      |  2 +-
 llvm/lib/Target/Mips/MipsISelLowering.cpp     | 12 ++---
 .../Target/NVPTX/NVPTXLowerUnreachable.cpp    |  2 +-
 llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp     |  2 +-
 llvm/lib/Target/PowerPC/PPCFastISel.cpp       |  2 +-
 .../PowerPC/PPCGenScalarMASSEntries.cpp       |  2 +-
 llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp   |  5 ++-
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp   |  2 +-
 .../Target/PowerPC/PPCLowerMASSVEntries.cpp   |  3 +-
 .../Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp |  5 ++-
 llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp     |  2 +-
 .../RISCV/RISCVGatherScatterLowering.cpp      |  8 ++--
 llvm/lib/Target/RISCV/RISCVTargetMachine.cpp  |  2 +-
 llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp   |  2 +-
 .../SystemZ/SystemZTargetTransformInfo.cpp    |  2 +-
 .../Target/X86/MCTargetDesc/X86AsmBackend.cpp |  4 +-
 llvm/lib/Target/X86/X86FrameLowering.cpp      |  3 +-
 llvm/lib/Target/X86/X86ISelDAGToDAG.cpp       |  6 +--
 llvm/lib/Target/X86/X86ISelLowering.cpp       |  2 +-
 .../Target/X86/X86InstCombineIntrinsic.cpp    | 38 ++++++++--------
 llvm/lib/Target/X86/X86Subtarget.cpp          |  2 +-
 .../lib/Target/X86/X86TargetTransformInfo.cpp |  2 +-
 llvm/lib/Transforms/Coroutines/CoroFrame.cpp  |  6 +--
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp  |  2 +-
 .../Transforms/IPO/Annotation2Metadata.cpp    |  2 +-
 llvm/lib/Transforms/IPO/Attributor.cpp        | 10 ++---
 .../Transforms/IPO/AttributorAttributes.cpp   | 14 +++---
 llvm/lib/Transforms/IPO/CrossDSOCFI.cpp       |  2 +-
 llvm/lib/Transforms/IPO/FunctionImport.cpp    |  4 +-
 .../Transforms/IPO/FunctionSpecialization.cpp |  6 +--
 llvm/lib/Transforms/IPO/GlobalSplit.cpp       |  2 +-
 llvm/lib/Transforms/IPO/HotColdSplitting.cpp  |  2 +-
 llvm/lib/Transforms/IPO/IROutliner.cpp        |  2 +-
 llvm/lib/Transforms/IPO/MergeFunctions.cpp    |  2 +-
 llvm/lib/Transforms/IPO/OpenMPOpt.cpp         |  2 +-
 .../Transforms/IPO/ThinLTOBitcodeWriter.cpp   |  8 ++--
 .../InstCombine/InstCombineCalls.cpp          |  5 ++-
 .../InstCombine/InstCombineCasts.cpp          |  2 +-
 .../InstCombine/InstCombineCompares.cpp       |  4 +-
 .../InstCombine/InstCombineShifts.cpp         |  6 +--
 .../InstCombine/InstCombineVectorOps.cpp      |  2 +-
 .../InstCombine/InstructionCombining.cpp      |  2 +-
 .../Instrumentation/AddressSanitizer.cpp      |  2 +-
 .../Instrumentation/BoundsChecking.cpp        |  2 +-
 .../Instrumentation/InstrProfiling.cpp        |  4 +-
 .../Instrumentation/MemProfiler.cpp           |  2 +-
 .../Instrumentation/MemorySanitizer.cpp       |  6 +--
 llvm/lib/Transforms/ObjCARC/ObjCARC.h         |  2 +-
 .../Transforms/ObjCARC/ObjCARCContract.cpp    |  2 +-
 llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp   |  6 +--
 .../Scalar/ConstraintElimination.cpp          |  2 +-
 .../Scalar/CorrelatedValuePropagation.cpp     |  2 +-
 .../Scalar/DeadStoreElimination.cpp           |  5 ++-
 llvm/lib/Transforms/Scalar/IndVarSimplify.cpp |  6 +--
 .../Transforms/Scalar/InferAddressSpaces.cpp  |  2 +-
 llvm/lib/Transforms/Scalar/JumpThreading.cpp  |  2 +-
 .../Transforms/Scalar/LoopInstSimplify.cpp    |  2 +-
 .../Transforms/Scalar/LoopStrengthReduce.cpp  | 13 +++---
 .../Scalar/LowerConstantIntrinsics.cpp        |  2 +-
 .../lib/Transforms/Scalar/MemCpyOptimizer.cpp | 10 ++---
 .../lib/Transforms/Scalar/NaryReassociate.cpp |  4 +-
 llvm/lib/Transforms/Scalar/NewGVN.cpp         | 15 ++++---
 llvm/lib/Transforms/Scalar/SROA.cpp           |  4 +-
 .../Scalar/SeparateConstOffsetFromGEP.cpp     |  2 +-
 .../Transforms/Scalar/SimpleLoopUnswitch.cpp  |  2 +-
 .../lib/Transforms/Scalar/SimplifyCFGPass.cpp |  2 +-
 .../Scalar/SpeculativeExecution.cpp           |  2 +-
 llvm/lib/Transforms/Scalar/StructurizeCFG.cpp |  2 +-
 .../Transforms/Utils/AssumeBundleBuilder.cpp  |  4 +-
 llvm/lib/Transforms/Utils/BasicBlockUtils.cpp |  4 +-
 .../Transforms/Utils/CallPromotionUtils.cpp   |  4 +-
 llvm/lib/Transforms/Utils/CloneFunction.cpp   |  6 +--
 llvm/lib/Transforms/Utils/CodeExtractor.cpp   |  6 +--
 .../Transforms/Utils/FunctionImportUtils.cpp  |  2 +-
 llvm/lib/Transforms/Utils/InlineFunction.cpp  | 14 +++---
 llvm/lib/Transforms/Utils/Local.cpp           | 14 +++---
 llvm/lib/Transforms/Utils/LoopUnroll.cpp      |  2 +-
 llvm/lib/Transforms/Utils/LoopUtils.cpp       |  2 +-
 .../Transforms/Utils/MemoryTaggingSupport.cpp |  2 +-
 llvm/lib/Transforms/Utils/PredicateInfo.cpp   | 10 ++---
 llvm/lib/Transforms/Utils/SCCPSolver.cpp      |  6 +--
 .../lib/Transforms/Utils/SimplifyLibCalls.cpp |  2 +-
 llvm/lib/Transforms/Utils/SplitModule.cpp     |  2 +-
 .../Vectorize/LoopVectorizationLegality.cpp   |  2 +-
 .../Transforms/Vectorize/LoopVectorize.cpp    |  8 ++--
 .../Transforms/Vectorize/SLPVectorizer.cpp    |  8 ++--
 llvm/lib/Transforms/Vectorize/VPlan.cpp       |  9 ++--
 llvm/lib/Transforms/Vectorize/VPlan.h         |  6 +--
 .../lib/Transforms/Vectorize/VPlanRecipes.cpp | 23 +++++-----
 .../Transforms/Vectorize/VPlanTransforms.cpp  | 15 ++++---
 .../Transforms/Vectorize/VectorCombine.cpp    |  4 +-
 .../llvm-reduce/deltas/ReduceDIMetadata.cpp   |  6 +--
 .../llvm-reduce/deltas/ReduceOpcodes.cpp      |  2 +-
 llvm/unittests/Analysis/LoopInfoTest.cpp      | 33 +++++++-------
 llvm/unittests/Analysis/MemorySSATest.cpp     |  6 +--
 .../Analysis/VectorFunctionABITest.cpp        |  2 +-
 .../unittests/CodeGen/AsmPrinterDwarfTest.cpp | 24 +++++-----
 llvm/unittests/CodeGen/DIETest.cpp            |  3 +-
 .../Frontend/OpenMPIRBuilderTest.cpp          | 15 ++++---
 llvm/unittests/IR/IRBuilderTest.cpp           |  2 +-
 llvm/unittests/IR/MetadataTest.cpp            |  7 +--
 llvm/unittests/Support/Casting.cpp            | 22 +++++-----
 .../Transforms/Utils/SSAUpdaterBulkTest.cpp   | 10 ++---
 llvm/utils/TableGen/CodeEmitterGen.cpp        |  6 +--
 llvm/utils/TableGen/CodeGenInstAlias.cpp      |  2 +-
 llvm/utils/TableGen/CodeGenRegisters.cpp      |  2 +-
 llvm/utils/TableGen/DecoderEmitter.cpp        |  4 +-
 llvm/utils/TableGen/VarLenCodeEmitterGen.cpp  |  2 +-
 212 files changed, 702 insertions(+), 667 deletions(-)

diff --git a/llvm/include/llvm/Analysis/SparsePropagation.h b/llvm/include/llvm/Analysis/SparsePropagation.h
index d5805a7314757f..1d58b82d57ff08 100644
--- a/llvm/include/llvm/Analysis/SparsePropagation.h
+++ b/llvm/include/llvm/Analysis/SparsePropagation.h
@@ -318,7 +318,7 @@ void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::getFeasibleSuccessors(
       return;
 
     Constant *C =
-        dyn_cast_or_null<Constant>(LatticeFunc->GetValueFromLatticeVal(
+        dyn_cast_if_present<Constant>(LatticeFunc->GetValueFromLatticeVal(
             std::move(BCValue), BI->getCondition()->getType()));
     if (!C || !isa<ConstantInt>(C)) {
       // Non-constant values can go either way.
@@ -356,8 +356,9 @@ void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::getFeasibleSuccessors(
   if (SCValue == LatticeFunc->getUndefVal())
     return;
 
-  Constant *C = dyn_cast_or_null<Constant>(LatticeFunc->GetValueFromLatticeVal(
-      std::move(SCValue), SI.getCondition()->getType()));
+  Constant *C =
+      dyn_cast_if_present<Constant>(LatticeFunc->GetValueFromLatticeVal(
+          std::move(SCValue), SI.getCondition()->getType()));
   if (!C || !isa<ConstantInt>(C)) {
     // All destinations are executable!
     Succs.assign(TI.getNumSuccessors(), true);
diff --git a/llvm/include/llvm/CodeGen/BasicTTIImpl.h b/llvm/include/llvm/CodeGen/BasicTTIImpl.h
index 5e7bdcdf72a49f..6528281be426e6 100644
--- a/llvm/include/llvm/CodeGen/BasicTTIImpl.h
+++ b/llvm/include/llvm/CodeGen/BasicTTIImpl.h
@@ -1730,7 +1730,7 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
       if (FOp) {
         if (ICA.getID() == Intrinsic::vp_load) {
           Align Alignment;
-          if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
+          if (auto *VPI = dyn_cast_if_present<VPIntrinsic>(ICA.getInst()))
             Alignment = VPI->getPointerAlignment().valueOrOne();
           unsigned AS = 0;
           if (ICA.getArgs().size() > 1)
@@ -1742,7 +1742,7 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
         }
         if (ICA.getID() == Intrinsic::vp_store) {
           Align Alignment;
-          if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
+          if (auto *VPI = dyn_cast_if_present<VPIntrinsic>(ICA.getInst()))
             Alignment = VPI->getPointerAlignment().valueOrOne();
           unsigned AS = 0;
           if (ICA.getArgs().size() >= 2)
diff --git a/llvm/include/llvm/CodeGen/GlobalISel/Utils.h b/llvm/include/llvm/CodeGen/GlobalISel/Utils.h
index ffb6e53a0363f9..ef81a1a3ea0221 100644
--- a/llvm/include/llvm/CodeGen/GlobalISel/Utils.h
+++ b/llvm/include/llvm/CodeGen/GlobalISel/Utils.h
@@ -254,7 +254,7 @@ Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI);
 template <class T>
 T *getOpcodeDef(Register Reg, const MachineRegisterInfo &MRI) {
   MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI);
-  return dyn_cast_or_null<T>(DefMI);
+  return dyn_cast_if_present<T>(DefMI);
 }
 
 /// Returns an APFloat from Val converted to the appropriate size.
diff --git a/llvm/include/llvm/IR/DebugInfoMetadata.h b/llvm/include/llvm/IR/DebugInfoMetadata.h
index f521862b1a54c2..c0cabf6927387d 100644
--- a/llvm/include/llvm/IR/DebugInfoMetadata.h
+++ b/llvm/include/llvm/IR/DebugInfoMetadata.h
@@ -1066,7 +1066,7 @@ class DIDerivedType : public DIType {
   DIType *getClassType() const;
 
   DIObjCProperty *getObjCProperty() const {
-    return dyn_cast_or_null<DIObjCProperty>(getExtraData());
+    return dyn_cast_if_present<DIObjCProperty>(getExtraData());
   }
 
   uint32_t getVBPtrOffset() const;
@@ -1244,33 +1244,33 @@ class DICompositeType : public DIType {
   }
   Metadata *getRawDataLocation() const { return getOperand(9); }
   DIVariable *getDataLocation() const {
-    return dyn_cast_or_null<DIVariable>(getRawDataLocation());
+    return dyn_cast_if_present<DIVariable>(getRawDataLocation());
   }
   DIExpression *getDataLocationExp() const {
-    return dyn_cast_or_null<DIExpression>(getRawDataLocation());
+    return dyn_cast_if_present<DIExpression>(getRawDataLocation());
   }
   Metadata *getRawAssociated() const { return getOperand(10); }
   DIVariable *getAssociated() const {
-    return dyn_cast_or_null<DIVariable>(getRawAssociated());
+    return dyn_cast_if_present<DIVariable>(getRawAssociated());
   }
   DIExpression *getAssociatedExp() const {
-    return dyn_cast_or_null<DIExpression>(getRawAssociated());
+    return dyn_cast_if_present<DIExpression>(getRawAssociated());
   }
   Metadata *getRawAllocated() const { return getOperand(11); }
   DIVariable *getAllocated() const {
-    return dyn_cast_or_null<DIVariable>(getRawAllocated());
+    return dyn_cast_if_present<DIVariable>(getRawAllocated());
   }
   DIExpression *getAllocatedExp() const {
-    return dyn_cast_or_null<DIExpression>(getRawAllocated());
+    return dyn_cast_if_present<DIExpression>(getRawAllocated());
   }
   Metadata *getRawRank() const { return getOperand(12); }
   ConstantInt *getRankConst() const {
-    if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
-      return dyn_cast_or_null<ConstantInt>(MD->getValue());
+    if (auto *MD = dyn_cast_if_present<ConstantAsMetadata>(getRawRank()))
+      return dyn_cast_if_present<ConstantInt>(MD->getValue());
     return nullptr;
   }
   DIExpression *getRankExp() const {
-    return dyn_cast_or_null<DIExpression>(getRawRank());
+    return dyn_cast_if_present<DIExpression>(getRawRank());
   }
 
   Metadata *getRawAnnotations() const { return getOperand(13); }
diff --git a/llvm/include/llvm/IR/InstrTypes.h b/llvm/include/llvm/IR/InstrTypes.h
index 6eba902fa04165..e6ca678aecc951 100644
--- a/llvm/include/llvm/IR/InstrTypes.h
+++ b/llvm/include/llvm/IR/InstrTypes.h
@@ -1479,7 +1479,7 @@ class CallBase : public Instruction {
   /// Returns the function called, or null if this is an indirect function
   /// invocation or the function signature does not match the call signature.
   Function *getCalledFunction() const {
-    if (auto *F = dyn_cast_or_null<Function>(getCalledOperand()))
+    if (auto *F = dyn_cast_if_present<Function>(getCalledOperand()))
       if (F->getValueType() == getFunctionType())
         return F;
     return nullptr;
diff --git a/llvm/include/llvm/IR/Metadata.h b/llvm/include/llvm/IR/Metadata.h
index 4498423c4c460d..8a727c9b7429f5 100644
--- a/llvm/include/llvm/IR/Metadata.h
+++ b/llvm/include/llvm/IR/Metadata.h
@@ -683,7 +683,7 @@ dyn_extract(Y &&MD) {
 template <class X, class Y>
 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
 dyn_extract_or_null(Y &&MD) {
-  if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
+  if (auto *V = dyn_cast_if_present<ConstantAsMetadata>(MD))
     return dyn_cast<X>(V->getValue());
   return nullptr;
 }
@@ -1539,11 +1539,11 @@ class AliasScopeNode {
   const MDNode *getDomain() const {
     if (Node->getNumOperands() < 2)
       return nullptr;
-    return dyn_cast_or_null<MDNode>(Node->getOperand(1));
+    return dyn_cast_if_present<MDNode>(Node->getOperand(1));
   }
   StringRef getName() const {
     if (Node->getNumOperands() > 2)
-      if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
+      if (MDString *N = dyn_cast_if_present<MDString>(Node->getOperand(2)))
         return N->getString();
     return StringRef();
   }
diff --git a/llvm/include/llvm/IR/PatternMatch.h b/llvm/include/llvm/IR/PatternMatch.h
index 096d1688af3f72..39c28d68dde5a7 100644
--- a/llvm/include/llvm/IR/PatternMatch.h
+++ b/llvm/include/llvm/IR/PatternMatch.h
@@ -239,8 +239,8 @@ struct apint_match {
     }
     if (V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
-        if (auto *CI =
-                dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndef))) {
+        if (auto *CI = dyn_cast_if_present<ConstantInt>(
+                C->getSplatValue(AllowUndef))) {
           Res = &CI->getValue();
           return true;
         }
@@ -265,7 +265,7 @@ struct apfloat_match {
     if (V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
         if (auto *CI =
-                dyn_cast_or_null<ConstantFP>(C->getSplatValue(AllowUndef))) {
+                dyn_cast_if_present<ConstantFP>(C->getSplatValue(AllowUndef))) {
           Res = &CI->getValueAPF();
           return true;
         }
@@ -337,7 +337,8 @@ struct cstval_pred_ty : public Predicate {
       return this->isValue(CV->getValue());
     if (const auto *VTy = dyn_cast<VectorType>(V->getType())) {
       if (const auto *C = dyn_cast<Constant>(V)) {
-        if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue()))
+        if (const auto *CV =
+                dyn_cast_if_present<ConstantVal>(C->getSplatValue()))
           return this->isValue(CV->getValue());
 
         // Number of elements of a scalable vector unknown at compile time
@@ -390,7 +391,7 @@ template <typename Predicate> struct api_pred_ty : public Predicate {
       }
     if (V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
-        if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
+        if (auto *CI = dyn_cast_if_present<ConstantInt>(C->getSplatValue()))
           if (this->isValue(CI->getValue())) {
             Res = &CI->getValue();
             return true;
@@ -416,7 +417,7 @@ template <typename Predicate> struct apf_pred_ty : public Predicate {
       }
     if (V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
-        if (auto *CI = dyn_cast_or_null<ConstantFP>(
+        if (auto *CI = dyn_cast_if_present<ConstantFP>(
                 C->getSplatValue(/* AllowUndef */ true)))
           if (this->isValue(CI->getValue())) {
             Res = &CI->getValue();
@@ -812,7 +813,7 @@ struct specific_fpval {
       return CFP->isExactlyValue(Val);
     if (V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
-        if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
+        if (auto *CFP = dyn_cast_if_present<ConstantFP>(C->getSplatValue()))
           return CFP->isExactlyValue(Val);
     return false;
   }
@@ -851,7 +852,7 @@ template <bool AllowUndefs> struct specific_intval {
     const auto *CI = dyn_cast<ConstantInt>(V);
     if (!CI && V->getType()->isVectorTy())
       if (const auto *C = dyn_cast<Constant>(V))
-        CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndefs));
+        CI = dyn_cast_if_present<ConstantInt>(C->getSplatValue(AllowUndefs));
 
     return CI && APInt::isSameValue(CI->getValue(), Val);
   }
diff --git a/llvm/include/llvm/IR/Statepoint.h b/llvm/include/llvm/IR/Statepoint.h
index 21c4a3eaa5ac2d..97f26b00b617c8 100644
--- a/llvm/include/llvm/IR/Statepoint.h
+++ b/llvm/include/llvm/IR/Statepoint.h
@@ -114,7 +114,7 @@ class GCStatepointInst : public CallBase {
   /// Returns the function called if this is a wrapping a direct call, and null
   /// otherwise.
   Function *getActualCalledFunction() const {
-    return dyn_cast_or_null<Function>(getActualCalledOperand());
+    return dyn_cast_if_present<Function>(getActualCalledOperand());
   }
 
   /// Return the type of the value returned by the call underlying the
diff --git a/llvm/include/llvm/ProfileData/InstrProfReader.h b/llvm/include/llvm/ProfileData/InstrProfReader.h
index ff50dfde0e7938..9471963cfba2ee 100644
--- a/llvm/include/llvm/ProfileData/InstrProfReader.h
+++ b/llvm/include/llvm/ProfileData/InstrProfReader.h
@@ -349,7 +349,7 @@ class RawInstrProfReader : public InstrProfReader {
                      const InstrProfCorrelator *Correlator,
                      std::function<void(Error)> Warn)
       : DataBuffer(std::move(DataBuffer)),
-        Correlator(dyn_cast_or_null<const InstrProfCorrelatorImpl<IntPtrT>>(
+        Correlator(dyn_cast_if_present<const InstrProfCorrelatorImpl<IntPtrT>>(
             Correlator)),
         Warn(Warn) {}
   RawInstrProfReader(const RawInstrProfReader &) = delete;
diff --git a/llvm/lib/Analysis/CallGraphSCCPass.cpp b/llvm/lib/Analysis/CallGraphSCCPass.cpp
index 307dddd51ece05..66ce1ea7e5c003 100644
--- a/llvm/lib/Analysis/CallGraphSCCPass.cpp
+++ b/llvm/lib/Analysis/CallGraphSCCPass.cpp
@@ -263,7 +263,7 @@ bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
 
       // If this call site is null, then the function pass deleted the call
       // entirely and the WeakTrackingVH nulled it out.
-      auto *Call = dyn_cast_or_null<CallBase>(*I->first);
+      auto *Call = dyn_cast_if_present<CallBase>(*I->first);
       if (!Call ||
           // If we've already seen this call site, then the FunctionPass RAUW'd
           // one call with another, which resulted in two "uses" in the edge
diff --git a/llvm/lib/Analysis/ConstantFolding.cpp b/llvm/lib/Analysis/ConstantFolding.cpp
index 90da3390eab324..6b57fdf4e5c464 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -87,7 +87,7 @@ static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
       continue;
     }
 
-    auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
+    auto *ElementCI = dyn_cast_if_present<ConstantInt>(Element);
     if (!ElementCI)
       return ConstantExpr::getBitCast(C, DestTy);
 
@@ -222,7 +222,7 @@ Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
           Src = Constant::getNullValue(
               cast<VectorType>(C->getType())->getElementType());
         else
-          Src = dyn_cast_or_null<ConstantInt>(Src);
+          Src = dyn_cast_if_present<ConstantInt>(Src);
         if (!Src)  // Reject constantexpr elements.
           return ConstantExpr::getBitCast(C, DestTy);
 
@@ -2490,7 +2490,7 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
     case Intrinsic::x86_sse2_cvtsd2si:
     case Intrinsic::x86_sse2_cvtsd2si64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/false, Ty,
                                            /*IsSigned*/true);
@@ -2500,7 +2500,7 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
     case Intrinsic::x86_sse2_cvttsd2si:
     case Intrinsic::x86_sse2_cvttsd2si64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/true, Ty,
                                            /*IsSigned*/true);
@@ -2882,7 +2882,7 @@ static Constant *ConstantFoldScalarCall2(StringRef Name,
     case Intrinsic::x86_avx512_vcvtsd2si32:
     case Intrinsic::x86_avx512_vcvtsd2si64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/false, Ty,
                                            /*IsSigned*/true);
@@ -2892,7 +2892,7 @@ static Constant *ConstantFoldScalarCall2(StringRef Name,
     case Intrinsic::x86_avx512_vcvtsd2usi32:
     case Intrinsic::x86_avx512_vcvtsd2usi64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/false, Ty,
                                            /*IsSigned*/false);
@@ -2902,7 +2902,7 @@ static Constant *ConstantFoldScalarCall2(StringRef Name,
     case Intrinsic::x86_avx512_cvttsd2si:
     case Intrinsic::x86_avx512_cvttsd2si64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/true, Ty,
                                            /*IsSigned*/true);
@@ -2912,7 +2912,7 @@ static Constant *ConstantFoldScalarCall2(StringRef Name,
     case Intrinsic::x86_avx512_cvttsd2usi:
     case Intrinsic::x86_avx512_cvttsd2usi64:
       if (ConstantFP *FPOp =
-              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+              dyn_cast_if_present<ConstantFP>(Op->getAggregateElement(0U)))
         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
                                            /*roundTowardZero=*/true, Ty,
                                            /*IsSigned*/false);
diff --git a/llvm/lib/Analysis/IVDescriptors.cpp b/llvm/lib/Analysis/IVDescriptors.cpp
index 1aa324c6b5f380..2c08425893aa54 100644
--- a/llvm/lib/Analysis/IVDescriptors.cpp
+++ b/llvm/lib/Analysis/IVDescriptors.cpp
@@ -974,7 +974,7 @@ bool RecurrenceDescriptor::isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop,
   // in the header will be dominated by the original phi, but need to be moved
   // after the non-phi previous value.
   SmallPtrSet<PHINode *, 4> SeenPhis;
-  while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
+  while (auto *PrevPhi = dyn_cast_if_present<PHINode>(Previous)) {
     if (PrevPhi->getParent() != Phi->getParent())
       return false;
     if (!SeenPhis.insert(PrevPhi).second)
diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp
index 7096e06d925ade..e083430f18acfd 100644
--- a/llvm/lib/Analysis/InlineCost.cpp
+++ b/llvm/lib/Analysis/InlineCost.cpp
@@ -1458,7 +1458,7 @@ bool CallAnalyzer::visitAlloca(AllocaInst &I) {
   // alloca and handle that case.
   if (I.isArrayAllocation()) {
     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
-    if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
+    if (auto *AllocSize = dyn_cast_if_present<ConstantInt>(Size)) {
       // Sometimes a dynamic alloca could be converted into a static alloca
       // after this constant prop, and become a huge static alloca on an
       // unconditional CFG path. Avoid inlining if this is going to happen above
@@ -1671,7 +1671,7 @@ bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
   auto *C = dyn_cast<Constant>(Arg);
 
   if (!C)
-    C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(Arg));
+    C = dyn_cast_if_present<Constant>(SimplifiedValues.lookup(Arg));
 
   Type *RT = CB.getFunctionType()->getReturnType();
   SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
@@ -1686,7 +1686,7 @@ bool CallAnalyzer::simplifyIntrinsicCallObjectSize(CallBase &CB) {
 
   Value *V = lowerObjectSizeCall(&cast<IntrinsicInst>(CB), DL, nullptr,
                                  /*MustSucceed=*/true);
-  Constant *C = dyn_cast_or_null<Constant>(V);
+  Constant *C = dyn_cast_if_present<Constant>(V);
   if (C)
     SimplifiedValues[&CB] = C;
   return C;
@@ -2120,7 +2120,7 @@ bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
     SimpleV =
         simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
 
-  if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
+  if (Constant *C = dyn_cast_if_present<Constant>(SimpleV))
     SimplifiedValues[&I] = C;
 
   if (SimpleV)
@@ -2151,7 +2151,7 @@ bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
   Value *SimpleV = simplifyFNegInst(
       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
 
-  if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
+  if (Constant *C = dyn_cast_if_present<Constant>(SimpleV))
     SimplifiedValues[&I] = C;
 
   if (SimpleV)
@@ -2236,7 +2236,7 @@ bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
   for (Value *I : Call.args()) {
     Constant *C = dyn_cast<Constant>(I);
     if (!C)
-      C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
+      C = dyn_cast_if_present<Constant>(SimplifiedValues.lookup(I));
     if (!C)
       return false; // This argument doesn't map to a constant.
 
@@ -2269,7 +2269,7 @@ bool CallAnalyzer::visitCallBase(CallBase &Call) {
     // Check if this happens to be an indirect function call to a known function
     // in this inline context. If not, we've done all we can.
     Value *Callee = Call.getCalledOperand();
-    F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
+    F = dyn_cast_if_present<Function>(SimplifiedValues.lookup(Callee));
     if (!F || F->getFunctionType() != Call.getFunctionType()) {
       onCallArgumentSetup(Call);
 
@@ -2370,7 +2370,7 @@ bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
   if (!FalseC)
     FalseC = SimplifiedValues.lookup(FalseVal);
   Constant *CondC =
-      dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
+      dyn_cast_if_present<Constant>(SimplifiedValues.lookup(SI.getCondition()));
 
   if (!CondC) {
     // Select C, X, X => X
@@ -2796,8 +2796,8 @@ InlineResult CallAnalyzer::analyze() {
     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
       if (BI->isConditional()) {
         Value *Cond = BI->getCondition();
-        if (ConstantInt *SimpleCond =
-                dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
+        if (ConstantInt *SimpleCond = dyn_cast_if_present<ConstantInt>(
+                SimplifiedValues.lookup(Cond))) {
           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
           BBWorklist.insert(NextBB);
           KnownSuccessors[BB] = NextBB;
@@ -2808,7 +2808,7 @@ InlineResult CallAnalyzer::analyze() {
     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
       Value *Cond = SI->getCondition();
       if (ConstantInt *SimpleCond =
-              dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
+              dyn_cast_if_present<ConstantInt>(SimplifiedValues.lookup(Cond))) {
         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
         BBWorklist.insert(NextBB);
         KnownSuccessors[BB] = NextBB;
diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp b/llvm/lib/Analysis/InstructionSimplify.cpp
index 2a45acf63aa2ca..d67aa45948d966 100644
--- a/llvm/lib/Analysis/InstructionSimplify.cpp
+++ b/llvm/lib/Analysis/InstructionSimplify.cpp
@@ -1001,7 +1001,7 @@ Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
                        const SimplifyQuery &Q, unsigned MaxRecurse) {
   Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
-  Constant *C = dyn_cast_or_null<Constant>(V);
+  Constant *C = dyn_cast_if_present<Constant>(V);
   return (C && C->isAllOnesValue());
 }
 
diff --git a/llvm/lib/Analysis/LazyValueInfo.cpp b/llvm/lib/Analysis/LazyValueInfo.cpp
index 910f6b72afefe2..b4bcc863f37b71 100644
--- a/llvm/lib/Analysis/LazyValueInfo.cpp
+++ b/llvm/lib/Analysis/LazyValueInfo.cpp
@@ -1278,9 +1278,8 @@ static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
   // Check if Usr can be simplified to a constant.
   if (auto *CI = dyn_cast<CastInst>(Usr)) {
     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
-    if (auto *C = dyn_cast_or_null<ConstantInt>(
-            simplifyCastInst(CI->getOpcode(), OpConst,
-                             CI->getDestTy(), DL))) {
+    if (auto *C = dyn_cast_if_present<ConstantInt>(
+            simplifyCastInst(CI->getOpcode(), OpConst, CI->getDestTy(), DL))) {
       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
     }
   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
@@ -1290,7 +1289,7 @@ static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
            "Operand 0 nor Operand 1 isn't a match");
     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
-    if (auto *C = dyn_cast_or_null<ConstantInt>(
+    if (auto *C = dyn_cast_if_present<ConstantInt>(
             simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
     }
@@ -1719,7 +1718,7 @@ getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
   Constant *Res = nullptr;
   if (Val.isConstant()) {
     Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
-    if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
+    if (ConstantInt *ResCI = dyn_cast_if_present<ConstantInt>(Res))
       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
     return LazyValueInfo::Unknown;
   }
diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index 0894560fd07898..1151d4f33f9172 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -2515,7 +2515,7 @@ void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
                                SymbolicStrides, UncomputablePtr, false);
   if (!CanDoRTIfNeeded) {
-    auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
+    auto *I = dyn_cast_if_present<Instruction>(UncomputablePtr);
     recordAnalysis("CantIdentifyArrayBounds", I) 
         << "cannot identify array bounds";
     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
@@ -2550,7 +2550,7 @@ void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
 
       // Check that we found the bounds for the pointer.
       if (!CanDoRTIfNeeded) {
-        auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
+        auto *I = dyn_cast_if_present<Instruction>(UncomputablePtr);
         recordAnalysis("CantCheckMemDepsAtRunTime", I)
             << "cannot check memory dependencies at runtime";
         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
@@ -2640,7 +2640,7 @@ void LoopAccessInfo::emitUnsafeDependenceRemark() {
 
   if (Instruction *I = Dep.getSource(*this)) {
     DebugLoc SourceLoc = I->getDebugLoc();
-    if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
+    if (auto *DD = dyn_cast_if_present<Instruction>(getPointerOperand(I)))
       SourceLoc = DD->getDebugLoc();
     if (SourceLoc)
       R << " Memory location is the same as accessed at "
diff --git a/llvm/lib/Analysis/LoopCacheAnalysis.cpp b/llvm/lib/Analysis/LoopCacheAnalysis.cpp
index c3a56639b5c8f8..58bf82854679d9 100644
--- a/llvm/lib/Analysis/LoopCacheAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopCacheAnalysis.cpp
@@ -243,7 +243,7 @@ IndexedReference::hasTemporalReuse(const IndexedReference &Other,
   int Levels = D->getLevels();
   for (int Level = 1; Level <= Levels; ++Level) {
     const SCEV *Distance = D->getDistance(Level);
-    const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
+    const SCEVConstant *SCEVConst = dyn_cast_if_present<SCEVConstant>(Distance);
 
     if (SCEVConst == nullptr) {
       LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: distance unknown\n");
diff --git a/llvm/lib/Analysis/LoopInfo.cpp b/llvm/lib/Analysis/LoopInfo.cpp
index 87ddfe3e92ae9a..589998f81079a2 100644
--- a/llvm/lib/Analysis/LoopInfo.cpp
+++ b/llvm/lib/Analysis/LoopInfo.cpp
@@ -173,7 +173,8 @@ PHINode *Loop::getCanonicalInductionVariable() const {
 /// Get the latch condition instruction.
 ICmpInst *Loop::getLatchCmpInst() const {
   if (BasicBlock *Latch = getLoopLatch())
-    if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
+    if (BranchInst *BI =
+            dyn_cast_if_present<BranchInst>(Latch->getTerminator()))
       if (BI->isConditional())
         return dyn_cast<ICmpInst>(BI->getCondition());
 
@@ -233,7 +234,7 @@ ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
   BasicBlock *Latch = L.getLoopLatch();
   assert(Latch && "Expecting valid latch");
 
-  BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
+  BranchInst *BI = dyn_cast_if_present<BranchInst>(Latch->getTerminator());
   assert(BI && BI->isConditional() && "Expecting conditional latch branch");
 
   ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
@@ -413,7 +414,7 @@ bool Loop::isCanonical(ScalarEvolution &SE) const {
   if (!getInductionDescriptor(SE, IndDesc))
     return false;
 
-  ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
+  ConstantInt *Init = dyn_cast_if_present<ConstantInt>(IndDesc.getStartValue());
   if (!Init || !Init->isZero())
     return false;
 
diff --git a/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp b/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
index 49eccde45f3172..41051dd8ded356 100644
--- a/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
+++ b/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
@@ -938,7 +938,7 @@ MemDepResult MemoryDependenceResults::getNonLocalInfoForBlock(
 
   bool isInvariantLoad = false;
 
-  if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
+  if (LoadInst *LI = dyn_cast_if_present<LoadInst>(QueryInst))
     isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
 
   // Do a binary search to see if we already have an entry for this block in
@@ -1081,7 +1081,7 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
   InitialNLPI.AATags = Loc.AATags;
 
   bool isInvariantLoad = false;
-  if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
+  if (LoadInst *LI = dyn_cast_if_present<LoadInst>(QueryInst))
     isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
 
   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
diff --git a/llvm/lib/Analysis/MemorySSA.cpp b/llvm/lib/Analysis/MemorySSA.cpp
index 2cf92ceba01032..4ebb3130369f97 100644
--- a/llvm/lib/Analysis/MemorySSA.cpp
+++ b/llvm/lib/Analysis/MemorySSA.cpp
@@ -307,13 +307,13 @@ instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
     }
   }
 
-  if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
+  if (auto *CB = dyn_cast_if_present<CallBase>(UseInst)) {
     ModRefInfo I = AA.getModRefInfo(DefInst, CB);
     return isModOrRefSet(I);
   }
 
   if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
-    if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
+    if (auto *UseLoad = dyn_cast_if_present<LoadInst>(UseInst))
       return !areLoadsReorderable(UseLoad, DefLoad);
 
   ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
diff --git a/llvm/lib/Analysis/MemorySSAUpdater.cpp b/llvm/lib/Analysis/MemorySSAUpdater.cpp
index 9ad60f774e9f86..ca0bfc6efae148 100644
--- a/llvm/lib/Analysis/MemorySSAUpdater.cpp
+++ b/llvm/lib/Analysis/MemorySSAUpdater.cpp
@@ -86,7 +86,7 @@ MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(
 
     // Now try to simplify the ops to avoid placing a phi.
     // This may return null if we never created a phi yet, that's okay
-    MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
+    MemoryPhi *Phi = dyn_cast_if_present<MemoryPhi>(MSSA->getMemoryAccess(BB));
 
     // See if we can avoid the phi by simplifying it.
     auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
@@ -445,14 +445,14 @@ void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
     // We just inserted a phi into this block, so the incoming value will become
     // the phi anyway, so it does not matter what we pass.
     for (auto &MP : InsertedPHIs) {
-      MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
+      MemoryPhi *Phi = dyn_cast_if_present<MemoryPhi>(MP);
       if (Phi)
         MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
     }
     // Existing Phi blocks may need renaming too, if an access was previously
     // optimized and the inserted Defs "covers" the Optimized value.
     for (const auto &MP : ExistingPhis) {
-      MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
+      MemoryPhi *Phi = dyn_cast_if_present<MemoryPhi>(MP);
       if (Phi)
         MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
     }
@@ -463,7 +463,7 @@ void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
   SmallPtrSet<const BasicBlock *, 8> Seen;
   SmallVector<const BasicBlock *, 16> Worklist;
   for (const auto &Var : Vars) {
-    MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
+    MemoryAccess *NewDef = dyn_cast_if_present<MemoryAccess>(Var);
     if (!NewDef)
       continue;
     // First, see if there is a local def after the operand.
@@ -620,7 +620,7 @@ void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
       // simplified, it may be a Use rather than a Def, so we cannot use MUD as
       // template. Calls coming from updateForClonedBlockIntoPred, ensure this.
       if (Instruction *NewInsn =
-              dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
+              dyn_cast_if_present<Instruction>(VMap.lookup(Insn))) {
         MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
             NewInsn,
             getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap,
diff --git a/llvm/lib/Analysis/MustExecute.cpp b/llvm/lib/Analysis/MustExecute.cpp
index d4b31f2b001878..982ade5b7933e7 100644
--- a/llvm/lib/Analysis/MustExecute.cpp
+++ b/llvm/lib/Analysis/MustExecute.cpp
@@ -145,7 +145,7 @@ static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
                                           IVStart, RHS,
                                           {DL, /*TLI*/ nullptr,
                                               DT, /*AC*/ nullptr, BI});
-  auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
+  auto *SimpleCst = dyn_cast_if_present<Constant>(SimpleValOrNull);
   if (!SimpleCst)
     return false;
   if (ExitBlock == BI->getSuccessor(0))
diff --git a/llvm/lib/Analysis/PHITransAddr.cpp b/llvm/lib/Analysis/PHITransAddr.cpp
index 5700fd664a4cd3..ee5ac59d25f396 100644
--- a/llvm/lib/Analysis/PHITransAddr.cpp
+++ b/llvm/lib/Analysis/PHITransAddr.cpp
@@ -308,7 +308,7 @@ Value *PHITransAddr::translateValue(BasicBlock *CurBB, BasicBlock *PredBB,
 
   if (MustDominate)
     // Make sure the value is live in the predecessor.
-    if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
+    if (Instruction *Inst = dyn_cast_if_present<Instruction>(Addr))
       if (!DT->dominates(Inst->getParent(), PredBB))
         Addr = nullptr;
 
diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp
index 580fe112fcd7bd..6e9003c40ed04e 100644
--- a/llvm/lib/Analysis/ScalarEvolution.cpp
+++ b/llvm/lib/Analysis/ScalarEvolution.cpp
@@ -9612,7 +9612,7 @@ const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
   const DataLayout &DL = getDataLayout();
   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
-    auto *CondVal = dyn_cast_or_null<ConstantInt>(
+    auto *CondVal = dyn_cast_if_present<ConstantInt>(
         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
 
     // Couldn't symbolically evaluate.
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index e4dc1a867f6f0c..1ad3ff31adf655 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -167,7 +167,7 @@ class TBAANodeImpl {
 
     if (Node->getNumOperands() < 2)
       return TBAANodeImpl<MDNodeTy>();
-    MDNodeTy *P = dyn_cast_or_null<MDNodeTy>(Node->getOperand(1));
+    MDNodeTy *P = dyn_cast_if_present<MDNodeTy>(Node->getOperand(1));
     if (!P)
       return TBAANodeImpl<MDNodeTy>();
     // Ok, this node has a valid parent. Return it.
@@ -220,11 +220,11 @@ class TBAAStructTagNodeImpl {
   }
 
   MDNodeTy *getBaseType() const {
-    return dyn_cast_or_null<MDNode>(Node->getOperand(0));
+    return dyn_cast_if_present<MDNode>(Node->getOperand(0));
   }
 
   MDNodeTy *getAccessType() const {
-    return dyn_cast_or_null<MDNode>(Node->getOperand(1));
+    return dyn_cast_if_present<MDNode>(Node->getOperand(1));
   }
 
   uint64_t getOffset() const {
@@ -323,7 +323,7 @@ class TBAAStructTypeNode {
                 ? 0
                 : mdconst::extract<ConstantInt>(Operands[2])->getZExtValue();
         Offset -= Cur;
-        MDNode *P = dyn_cast_or_null<MDNode>(Operands[1]);
+        MDNode *P = dyn_cast_if_present<MDNode>(Operands[1]);
         if (!P)
           return TBAAStructTypeNode();
         return TBAAStructTypeNode(P);
@@ -353,7 +353,7 @@ class TBAAStructTypeNode {
     uint64_t Cur =
         mdconst::extract<ConstantInt>(Operands[TheIdx + 1])->getZExtValue();
     Offset -= Cur;
-    MDNode *P = dyn_cast_or_null<MDNode>(Operands[TheIdx]);
+    MDNode *P = dyn_cast_if_present<MDNode>(Operands[TheIdx]);
     if (!P)
       return TBAAStructTypeNode();
     return TBAAStructTypeNode(P);
diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index 9ae05a4b5ccc72..600881ed14cc11 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -1840,7 +1840,7 @@ void computeKnownBits(const Value *V, const APInt &DemandedElts,
       Constant *Element = CV->getAggregateElement(i);
       if (isa<PoisonValue>(Element))
         continue;
-      auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
+      auto *ElementCI = dyn_cast_if_present<ConstantInt>(Element);
       if (!ElementCI) {
         Known.resetAll();
         return;
@@ -3274,7 +3274,7 @@ static unsigned computeNumSignBitsVectorConstant(const Value *V,
     if (!DemandedElts[i])
       continue;
     // If we find a non-ConstantInt, bail out.
-    auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
+    auto *Elt = dyn_cast_if_present<ConstantInt>(CV->getAggregateElement(i));
     if (!Elt)
       return 0;
 
@@ -3756,7 +3756,7 @@ static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
     if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
       unsigned NumElts = CVFVTy->getNumElements();
       for (unsigned i = 0; i != NumElts; ++i) {
-        auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
+        auto *CFP = dyn_cast_if_present<ConstantFP>(CV->getAggregateElement(i));
         if (!CFP)
           return false;
         if (CFP->getValueAPF().isNegative() &&
@@ -4349,7 +4349,7 @@ void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
 
   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
 
-  if (auto *CFP = dyn_cast_or_null<ConstantFP>(V)) {
+  if (auto *CFP = dyn_cast_if_present<ConstantFP>(V)) {
     Known.KnownFPClasses = CFP->getValueAPF().classify();
     Known.SignBit = CFP->isNegative();
     return;
@@ -4391,7 +4391,7 @@ void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
     KnownNotFromFlags |= Arg->getNoFPClass();
 
   const Operator *Op = dyn_cast<Operator>(V);
-  if (const FPMathOperator *FPOp = dyn_cast_or_null<FPMathOperator>(Op)) {
+  if (const FPMathOperator *FPOp = dyn_cast_if_present<FPMathOperator>(Op)) {
     if (FPOp->hasNoNaNs())
       KnownNotFromFlags |= fcNan;
     if (FPOp->hasNoInfs())
@@ -6548,7 +6548,7 @@ static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
     ShiftAmounts.push_back(C);
 
   bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
-    auto *CI = dyn_cast_or_null<ConstantInt>(C);
+    auto *CI = dyn_cast_if_present<ConstantInt>(C);
     return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
   });
 
@@ -6884,10 +6884,10 @@ static bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
     auto *TI = Dominator->getBlock()->getTerminator();
 
     Value *Cond = nullptr;
-    if (auto BI = dyn_cast_or_null<BranchInst>(TI)) {
+    if (auto BI = dyn_cast_if_present<BranchInst>(TI)) {
       if (BI->isConditional())
         Cond = BI->getCondition();
-    } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
+    } else if (auto SI = dyn_cast_if_present<SwitchInst>(TI)) {
       Cond = SI->getCondition();
     }
 
diff --git a/llvm/lib/AsmParser/LLParser.cpp b/llvm/lib/AsmParser/LLParser.cpp
index fb9e1ba875e1fa..3145d39f27ccc8 100644
--- a/llvm/lib/AsmParser/LLParser.cpp
+++ b/llvm/lib/AsmParser/LLParser.cpp
@@ -3448,12 +3448,12 @@ bool LLParser::PerFunctionState::setInstName(int NameID,
 /// forward reference record if needed.
 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
                                               LocTy Loc) {
-  return dyn_cast_or_null<BasicBlock>(
+  return dyn_cast_if_present<BasicBlock>(
       getVal(Name, Type::getLabelTy(F.getContext()), Loc));
 }
 
 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
-  return dyn_cast_or_null<BasicBlock>(
+  return dyn_cast_if_present<BasicBlock>(
       getVal(ID, Type::getLabelTy(F.getContext()), Loc));
 }
 
@@ -3760,7 +3760,7 @@ bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
       if (Label.Kind == ValID::t_LocalID)
         return error(Label.Loc, "cannot take address of numeric label after "
                                 "the function is defined");
-      BB = dyn_cast_or_null<BasicBlock>(
+      BB = dyn_cast_if_present<BasicBlock>(
           F->getValueSymbolTable()->lookup(Label.StrVal));
       if (!BB)
         return error(Label.Loc, "referenced value is not a basic block");
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index 8907f6fa4ff3fd..cbc3b3753a0752 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -3295,7 +3295,7 @@ Error BitcodeReader::parseConstants() {
         BaseType = getTypeByID(BaseTypeID);
       }
 
-      PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
+      PointerType *OrigPtrTy = dyn_cast_if_present<PointerType>(BaseType);
       if (!OrigPtrTy)
         return error("GEP base operand must be pointer or vector of pointer");
 
@@ -3325,8 +3325,7 @@ Error BitcodeReader::parseConstants() {
       if (Record.size() < 3)
         return error("Invalid extractelement constexpr record");
       unsigned OpTyID = Record[0];
-      VectorType *OpTy =
-        dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
+      VectorType *OpTy = dyn_cast_if_present<VectorType>(getTypeByID(OpTyID));
       if (!OpTy)
         return error("Invalid extractelement constexpr record");
       unsigned IdxRecord;
@@ -3377,7 +3376,7 @@ Error BitcodeReader::parseConstants() {
     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
       VectorType *RTy = dyn_cast<VectorType>(CurTy);
       VectorType *OpTy =
-        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
+          dyn_cast_if_present<VectorType>(getTypeByID(Record[0]));
       if (Record.size() < 4 || !RTy || !OpTy)
         return error("Invalid shufflevector constexpr record");
       V = BitcodeConstant::create(
@@ -3491,7 +3490,8 @@ Error BitcodeReader::parseConstants() {
       if (Record.size() < 3)
         return error("Invalid inlineasm record");
       unsigned OpNum = 0;
-      auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
+      auto *FnTy =
+          dyn_cast_if_present<FunctionType>(getTypeByID(Record[OpNum]));
       ++OpNum;
       if (!FnTy)
         return error("Invalid inlineasm record");
@@ -4838,13 +4838,13 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
 
       MDNode *Scope = nullptr, *IA = nullptr;
       if (ScopeID) {
-        Scope = dyn_cast_or_null<MDNode>(
+        Scope = dyn_cast_if_present<MDNode>(
             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
         if (!Scope)
           return error("Invalid record");
       }
       if (IAID) {
-        IA = dyn_cast_or_null<MDNode>(
+        IA = dyn_cast_if_present<MDNode>(
             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
         if (!IA)
           return error("Invalid record");
@@ -5514,8 +5514,8 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
       InstructionList.push_back(SI);
       for (unsigned i = 0, e = NumCases; i != e; ++i) {
-        ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
-            getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
+        ConstantInt *CaseVal = dyn_cast_if_present<ConstantInt>(
+            getFnValueByID(Record[3 + i * 2], OpTy, OpTyID, nullptr));
         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
         if (!CaseVal || !DestBB) {
           delete SI;
@@ -5579,7 +5579,7 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
         return error("Callee is not a pointer");
       if (!FTy) {
         FTyID = getContainedTypeID(CalleeTypeID);
-        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
+        FTy = dyn_cast_if_present<FunctionType>(getTypeByID(FTyID));
         if (!FTy)
           return error("Callee is not of pointer to function type");
       }
@@ -5657,7 +5657,7 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
       FunctionType *FTy = nullptr;
       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
         FTyID = Record[OpNum++];
-        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
+        FTy = dyn_cast_if_present<FunctionType>(getTypeByID(FTyID));
         if (!FTy)
           return error("Explicit call type is not a function type");
       }
@@ -5673,7 +5673,7 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
         return error("Callee is not a pointer type");
       if (!FTy) {
         FTyID = getContainedTypeID(CalleeTypeID);
-        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
+        FTy = dyn_cast_if_present<FunctionType>(getTypeByID(FTyID));
         if (!FTy)
           return error("Callee is not of pointer to function type");
       }
@@ -6370,7 +6370,7 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
       FunctionType *FTy = nullptr;
       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
         FTyID = Record[OpNum++];
-        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
+        FTy = dyn_cast_if_present<FunctionType>(getTypeByID(FTyID));
         if (!FTy)
           return error("Explicit call type is not a function type");
       }
@@ -6386,7 +6386,7 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
         return error("Callee is not a pointer type");
       if (!FTy) {
         FTyID = getContainedTypeID(CalleeTypeID);
-        FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
+        FTy = dyn_cast_if_present<FunctionType>(getTypeByID(FTyID));
         if (!FTy)
           return error("Callee is not of pointer to function type");
       }
@@ -6545,7 +6545,8 @@ Error BitcodeReader::parseFunctionBody(Function *F) {
     if (!A->getParent()) {
       // We found at least one unresolved value.  Nuke them all to avoid leaks.
       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
-        if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
+        if ((A = dyn_cast_if_present<Argument>(ValueList[i])) &&
+            !A->getParent()) {
           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
           delete A;
         }
diff --git a/llvm/lib/Bitcode/Reader/MetadataLoader.cpp b/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
index 910e97489dbbe0..df3c597954f515 100644
--- a/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
+++ b/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
@@ -229,14 +229,14 @@ Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
 
 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
   Metadata *MD = lookup(Idx);
-  if (auto *N = dyn_cast_or_null<MDNode>(MD))
+  if (auto *N = dyn_cast_if_present<MDNode>(MD))
     if (!N->isResolved())
       return nullptr;
   return MD;
 }
 
 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
-  return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
+  return dyn_cast_if_present<MDNode>(getMetadataFwdRef(Idx));
 }
 
 void BitcodeReaderMetadataList::tryToResolveCycles() {
@@ -273,7 +273,7 @@ void BitcodeReaderMetadataList::tryToResolveCycles() {
   // Resolve any cycles.
   for (unsigned I : UnresolvedNodes) {
     auto &MD = MetadataPtrs[I];
-    auto *N = dyn_cast_or_null<MDNode>(MD);
+    auto *N = dyn_cast_if_present<MDNode>(MD);
     if (!N)
       continue;
 
@@ -295,7 +295,7 @@ void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
 }
 
 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
-  auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
+  auto *UUID = dyn_cast_if_present<MDString>(MaybeUUID);
   if (LLVM_LIKELY(!UUID))
     return MaybeUUID;
 
@@ -309,7 +309,7 @@ Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
 }
 
 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
-  auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
+  auto *Tuple = dyn_cast_if_present<MDTuple>(MaybeTuple);
   if (!Tuple || Tuple->isDistinct())
     return MaybeTuple;
 
@@ -326,7 +326,7 @@ Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
 }
 
 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
-  auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
+  auto *Tuple = dyn_cast_if_present<MDTuple>(MaybeTuple);
   if (!Tuple || Tuple->isDistinct())
     return MaybeTuple;
 
@@ -366,7 +366,7 @@ class PlaceholderQueue {
         Temporaries.insert(ID);
         continue;
       }
-      auto *N = dyn_cast_or_null<MDNode>(MD);
+      auto *N = dyn_cast_if_present<MDNode>(MD);
       if (N && N->isTemporary())
         Temporaries.insert(ID);
     }
@@ -484,9 +484,9 @@ class MetadataLoader::MetadataLoaderImpl {
   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
   void upgradeCUSubprograms() {
     for (auto CU_SP : CUSubprograms)
-      if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
+      if (auto *SPs = dyn_cast_if_present<MDTuple>(CU_SP.second))
         for (auto &Op : SPs->operands())
-          if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
+          if (auto *SP = dyn_cast_if_present<DISubprogram>(Op))
             SP->replaceUnit(CU_SP.first);
     CUSubprograms.clear();
   }
@@ -500,10 +500,11 @@ class MetadataLoader::MetadataLoaderImpl {
     if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
       for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
         auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
-        if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
+        if (auto *GVs =
+                dyn_cast_if_present<MDTuple>(CU->getRawGlobalVariables()))
           for (unsigned I = 0; I < GVs->getNumOperands(); I++)
             if (auto *GV =
-                    dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
+                    dyn_cast_if_present<DIGlobalVariable>(GVs->getOperand(I))) {
               auto *DGVE = DIGlobalVariableExpression::getDistinct(
                   Context, GV, DIExpression::get(Context, {}));
               GVs->replaceOperandWith(I, DGVE);
@@ -535,12 +536,12 @@ class MetadataLoader::MetadataLoaderImpl {
     DILocalScope *InitialScope = S;
     DenseSet<DILocalScope *> Visited;
     while (S && !isa<DISubprogram>(S)) {
-      S = dyn_cast_or_null<DILocalScope>(S->getScope());
+      S = dyn_cast_if_present<DILocalScope>(S->getScope());
       if (Visited.contains(S))
         break;
       Visited.insert(S);
     }
-    ParentSubprogram[InitialScope] = llvm::dyn_cast_or_null<DISubprogram>(S);
+    ParentSubprogram[InitialScope] = llvm::dyn_cast_if_present<DISubprogram>(S);
 
     return ParentSubprogram[InitialScope];
   }
@@ -559,7 +560,7 @@ class MetadataLoader::MetadataLoaderImpl {
           SetVector<Metadata *> EntitiesToRemove;
           for (Metadata *Op : CU->getImportedEntities()->operands()) {
             auto *IE = cast<DIImportedEntity>(Op);
-            if (dyn_cast_or_null<DILocalScope>(IE->getScope())) {
+            if (dyn_cast_if_present<DILocalScope>(IE->getScope())) {
               EntitiesToRemove.insert(IE);
             }
           }
@@ -1869,7 +1870,7 @@ Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
 
     // Upgrade sp->function mapping to function->sp mapping.
     if (HasFn) {
-      if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
+      if (auto *CMD = dyn_cast_if_present<ConstantAsMetadata>(CUorFn))
         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
           if (F->isMaterializable())
             // Defer until materialized; unmaterialized functions may not have
@@ -2044,7 +2045,7 @@ Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
         AlignInBits = Record[11];
       }
       GlobalVariable *Attach = nullptr;
-      if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
+      if (auto *CMD = dyn_cast_if_present<ConstantAsMetadata>(Expr)) {
         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
           Attach = GV;
           Expr = nullptr;
@@ -2308,7 +2309,7 @@ Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
     if (K == MDKindMap.end())
       return error("Invalid ID");
     MDNode *MD =
-        dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
+        dyn_cast_if_present<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
     if (!MD)
       return error("Invalid metadata attachment: expect fwd ref to MDNode");
     GO.addMetadata(K->second, *MD);
@@ -2386,7 +2387,7 @@ Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
           // Drop the attachment.  This used to be legal, but there's no
           // upgrade path.
           break;
-        MDNode *MD = dyn_cast_or_null<MDNode>(Node);
+        MDNode *MD = dyn_cast_if_present<MDNode>(Node);
         if (!MD)
           return error("Invalid metadata attachment");
 
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 61309c51336e52..e32fe9ef7c1523 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -3372,7 +3372,7 @@ static void emitGlobalConstantVector(const DataLayout &DL,
     // here, just use the existing code in ConstantFolding.
     Type *IntT =
         IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
-    ConstantInt *CI = dyn_cast_or_null<ConstantInt>(ConstantFoldConstant(
+    ConstantInt *CI = dyn_cast_if_present<ConstantInt>(ConstantFoldConstant(
         ConstantExpr::getBitCast(const_cast<ConstantVector *>(CV), IntT), DL));
     if (!CI) {
       report_fatal_error(
@@ -3570,7 +3570,7 @@ static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
     return;
 
-  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
+  const GlobalValue *BaseGV = dyn_cast_if_present<GlobalValue>(BaseCst);
   if (!BaseGV)
     return;
 
diff --git a/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
index dddc08b3bc0166..a5e4f5be8e7cfb 100644
--- a/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -398,7 +398,7 @@ TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
 
   const DIScope *Scope = SP->getScope();
   TypeIndex TI;
-  if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
+  if (const auto *Class = dyn_cast_if_present<DICompositeType>(Scope)) {
     // If the scope is a DICompositeType, then this must be a method. Member
     // function types take some special handling, and require access to the
     // subprogram.
@@ -433,7 +433,7 @@ getFunctionOptions(const DISubroutineType *Ty,
 
   // Add CxxReturnUdt option to functions that return nontrivial record types
   // or methods that return record types.
-  if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
+  if (auto *ReturnDCTy = dyn_cast_if_present<DICompositeType>(ReturnTy))
     if (isNonTrivial(ReturnDCTy) || ClassTy)
       FO |= FunctionOptions::CxxReturnUdt;
 
@@ -2116,7 +2116,7 @@ TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
   TypeIndex ThisTypeIndex;
   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
     if (const DIDerivedType *PtrTy =
-            dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
+            dyn_cast_if_present<DIDerivedType>(ReturnAndArgs[Index])) {
       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
         Index++;
@@ -2274,7 +2274,7 @@ TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
     for (const DINode *Element : Ty->getElements()) {
       // We assume that the frontend provides all members in source declaration
       // order, which is what MSVC does.
-      if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
+      if (auto *Enumerator = dyn_cast_if_present<DIEnumerator>(Element)) {
         // FIXME: Is it correct to always emit these as unsigned here?
         EnumeratorRecord ER(MemberAccess::Public,
                             APSInt(Enumerator->getValue(), true),
@@ -2601,8 +2601,8 @@ CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
         Member->getOffsetInBits() + MemberInfo.BaseOffset;
     if (Member->isBitField()) {
       uint64_t StartBitOffset = MemberOffsetInBits;
-      if (const auto *CI =
-              dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
+      if (const auto *CI = dyn_cast_if_present<ConstantInt>(
+              Member->getStorageOffsetInBits())) {
         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
       }
       StartBitOffset -= MemberOffsetInBits;
@@ -3375,11 +3375,11 @@ void CodeViewDebug::emitStaticConstMemberList() {
 
     APSInt Value;
     if (const ConstantInt *CI =
-            dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
+            dyn_cast_if_present<ConstantInt>(DTy->getConstant()))
       Value = APSInt(CI->getValue(),
                      DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
     else if (const ConstantFP *CFP =
-                 dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
+                 dyn_cast_if_present<ConstantFP>(DTy->getConstant()))
       Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
     else
       llvm_unreachable("cannot emit a constant without a value");
@@ -3413,7 +3413,7 @@ void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
 
   const DIScope *Scope = DIGV->getScope();
   // For static data members, get the scope from the declaration.
-  if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
+  if (const auto *MemberDecl = dyn_cast_if_present<DIDerivedType>(
           DIGV->getRawStaticDataMemberDeclaration()))
     Scope = MemberDecl->getScope();
   // For static local variables and Fortran, the scoping portion is elided
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
index d462859e489465..966d2d60f3a834 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
@@ -926,8 +926,8 @@ void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
           // When emitting a variant part, wrap each member in
           // DW_TAG_variant.
           DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
-          if (const ConstantInt *CI =
-              dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
+          if (const ConstantInt *CI = dyn_cast_if_present<ConstantInt>(
+                  DDTy->getDiscriminantValue())) {
             if (DD->isUnsignedDIType(Discriminator->getBaseType()))
               addUInt(Variant, dwarf::DW_AT_discr_value, std::nullopt,
                       CI->getZExtValue());
@@ -1538,7 +1538,7 @@ void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
   DINodeArray Elements = CTy->getElements();
   for (DINode *E : Elements) {
     // FIXME: Should this really be such a loose cast?
-    if (auto *Element = dyn_cast_or_null<DINode>(E)) {
+    if (auto *Element = dyn_cast_if_present<DINode>(E)) {
       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
       else if (Element->getTag() == dwarf::DW_TAG_generic_subrange)
@@ -1565,7 +1565,7 @@ void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
 
   // Add enumerators to enumeration type.
   for (const DINode *E : Elements) {
-    auto *Enum = dyn_cast_or_null<DIEnumerator>(E);
+    auto *Enum = dyn_cast_if_present<DIEnumerator>(E);
     if (Enum) {
       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
       StringRef Name = Enum->getName();
@@ -1729,9 +1729,11 @@ DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
   // public if the parent is something else.
   addAccess(StaticMemberDIE, DT->getFlags());
 
-  if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
+  if (const ConstantInt *CI =
+          dyn_cast_if_present<ConstantInt>(DT->getConstant()))
     addConstantValue(StaticMemberDIE, CI, Ty);
-  if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
+  if (const ConstantFP *CFP =
+          dyn_cast_if_present<ConstantFP>(DT->getConstant()))
     addConstantFPValue(StaticMemberDIE, CFP);
 
   if (uint32_t AlignInBytes = DT->getAlignInBytes())
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 6e99fb133e26a9..fe6a88ff709c92 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -5585,8 +5585,8 @@ bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
     // non-integral pointers, so in that case bail out now.
     Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
     Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
-    PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
-    PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
+    PointerType *BasePtrTy = dyn_cast_if_present<PointerType>(BaseTy);
+    PointerType *ScalePtrTy = dyn_cast_if_present<PointerType>(ScaleTy);
     if (DL->isNonIntegralPointerType(Addr->getType()) ||
         (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
         (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
@@ -5629,7 +5629,7 @@ bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
         // the original IR value was tossed in favor of a constant back when
         // the AddrMode was created we need to bail out gracefully if widths
         // do not match instead of extending it.
-        Instruction *I = dyn_cast_or_null<Instruction>(Result);
+        Instruction *I = dyn_cast_if_present<Instruction>(Result);
         if (I && (Result != AddrMode.BaseReg))
           I->eraseFromParent();
         return Modified;
@@ -5738,7 +5738,7 @@ bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
         return false;
       if (isa<VectorType>(C->getType()))
         C = C->getSplatValue();
-      auto *CI = dyn_cast_or_null<ConstantInt>(C);
+      auto *CI = dyn_cast_if_present<ConstantInt>(C);
       if (!CI || !CI->isZero())
         return false;
       // Scalarize the index if needed.
@@ -8460,7 +8460,7 @@ bool CodeGenPrepare::placeDbgValues(Function &F) {
   auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
     SmallVector<Instruction *, 4> VIs;
     for (Value *V : DbgItem->location_ops())
-      if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
+      if (Instruction *VI = dyn_cast_if_present<Instruction>(V))
         VIs.push_back(VI);
 
     // This item may depend on multiple instructions, complicating any
diff --git a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
index 91a64d59e154df..0b2bbbfb7e41be 100644
--- a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
@@ -5159,7 +5159,7 @@ bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
   }
 
   auto CheckEltValue = [&](const Constant *C) {
-    if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
+    if (auto *CI = dyn_cast_if_present<ConstantInt>(C))
       return !CI->isZero();
     return false;
   };
diff --git a/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp b/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
index 37e7153be5720e..a0362cfbd50c11 100644
--- a/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
@@ -6026,7 +6026,7 @@ static bool isNonZeroModBitWidthOrUndef(const MachineRegisterInfo &MRI,
       MRI, Reg,
       [=](const Constant *C) {
         // Null constant here means an undef.
-        const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C);
+        const ConstantInt *CI = dyn_cast_if_present<ConstantInt>(C);
         return !CI || CI->getValue().urem(BW) != 0;
       },
       /*AllowUndefs*/ true);
diff --git a/llvm/lib/CodeGen/GlobalISel/Utils.cpp b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
index eaf829f562b2dc..de8dd887381f79 100644
--- a/llvm/lib/CodeGen/GlobalISel/Utils.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
@@ -716,7 +716,7 @@ bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF,
                                   const MachinePointerInfo &MPO) {
   auto PSV = dyn_cast_if_present<const PseudoSourceValue *>(MPO.V);
-  if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) {
+  if (auto FSPV = dyn_cast_if_present<FixedStackPseudoSourceValue>(PSV)) {
     MachineFrameInfo &MFI = MF.getFrameInfo();
     return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
                            MPO.Offset);
diff --git a/llvm/lib/CodeGen/LowerEmuTLS.cpp b/llvm/lib/CodeGen/LowerEmuTLS.cpp
index f3b5069d351b4e..d931843e9fa51a 100644
--- a/llvm/lib/CodeGen/LowerEmuTLS.cpp
+++ b/llvm/lib/CodeGen/LowerEmuTLS.cpp
@@ -133,7 +133,7 @@ bool LowerEmuTLS::addEmuTlsVar(Module &M, const GlobalVariable *GV) {
   GlobalVariable *EmuTlsTmplVar = nullptr;
   if (InitValue) {
     std::string EmuTlsTmplName = ("__emutls_t." + GV->getName()).str();
-    EmuTlsTmplVar = dyn_cast_or_null<GlobalVariable>(
+    EmuTlsTmplVar = dyn_cast_if_present<GlobalVariable>(
         M.getOrInsertGlobal(EmuTlsTmplName, GVType));
     assert(EmuTlsTmplVar && "Failed to create emualted TLS initializer");
     EmuTlsTmplVar->setConstant(true);
diff --git a/llvm/lib/CodeGen/MIRParser/MIParser.cpp b/llvm/lib/CodeGen/MIRParser/MIParser.cpp
index ede4291fe26dc9..53542882242ce5 100644
--- a/llvm/lib/CodeGen/MIRParser/MIParser.cpp
+++ b/llvm/lib/CodeGen/MIRParser/MIParser.cpp
@@ -773,7 +773,7 @@ bool MIParser::parseBasicBlockDefinition(
     return true;
 
   if (!Name.empty()) {
-    BB = dyn_cast_or_null<BasicBlock>(
+    BB = dyn_cast_if_present<BasicBlock>(
         MF.getFunction().getValueSymbolTable()->lookup(Name));
     if (!BB)
       return error(Loc, Twine("basic block '") + Name +
@@ -2615,7 +2615,7 @@ bool MIParser::parseCFIOperand(MachineOperand &Dest) {
 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
   switch (Token.kind()) {
   case MIToken::NamedIRBlock: {
-    BB = dyn_cast_or_null<BasicBlock>(
+    BB = dyn_cast_if_present<BasicBlock>(
         F.getValueSymbolTable()->lookup(Token.stringValue()));
     if (!BB)
       return error(Twine("use of undefined IR block '") + Token.range() + "'");
diff --git a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
index 78d7e62797ce5f..d09475bc8e5cfb 100644
--- a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
+++ b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
@@ -253,7 +253,7 @@ MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
   // Parse the block scalar manually so that we can return unique pointer
   // without having to go trough YAML traits.
   if (const auto *BSN =
-          dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
+          dyn_cast_if_present<yaml::BlockScalarNode>(In.getCurrentNode())) {
     SMDiagnostic Error;
     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
                       Context, &IRSlots, DataLayoutCallback);
@@ -826,7 +826,7 @@ bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
     const AllocaInst *Alloca = nullptr;
     const yaml::StringValue &Name = Object.Name;
     if (!Name.Value.empty()) {
-      Alloca = dyn_cast_or_null<AllocaInst>(
+      Alloca = dyn_cast_if_present<AllocaInst>(
           F.getValueSymbolTable()->lookup(Name.Value));
       if (!Alloca)
         return error(Name.SourceRange.Start,
@@ -970,7 +970,7 @@ bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
       // FIXME: Support target-specific constant pools
       return error(YamlConstant.Value.SourceRange.Start,
                    "Can't parse target-specific constant pool entries yet");
-    const Constant *Value = dyn_cast_or_null<Constant>(
+    const Constant *Value = dyn_cast_if_present<Constant>(
         parseConstantValue(YamlConstant.Value.Value, Error, M));
     if (!Value)
       return error(Error, YamlConstant.Value.SourceRange);
diff --git a/llvm/lib/CodeGen/MachineFunction.cpp b/llvm/lib/CodeGen/MachineFunction.cpp
index 57af571ed9bfd5..070cb208f151a3 100644
--- a/llvm/lib/CodeGen/MachineFunction.cpp
+++ b/llvm/lib/CodeGen/MachineFunction.cpp
@@ -114,7 +114,7 @@ void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
     return;
 
   auto *Existing =
-      dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
+      dyn_cast_if_present<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
 
   if (!Existing || Existing->getNumOperands() != 2)
     return;
diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
index 5be1892a44f6dd..6b3a904fd38aa0 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
@@ -12581,32 +12581,32 @@ bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
 ConstantSDNode *
 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
                                         BitVector *UndefElements) const {
-  return dyn_cast_or_null<ConstantSDNode>(
+  return dyn_cast_if_present<ConstantSDNode>(
       getSplatValue(DemandedElts, UndefElements));
 }
 
 ConstantSDNode *
 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
-  return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
+  return dyn_cast_if_present<ConstantSDNode>(getSplatValue(UndefElements));
 }
 
 ConstantFPSDNode *
 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
                                           BitVector *UndefElements) const {
-  return dyn_cast_or_null<ConstantFPSDNode>(
+  return dyn_cast_if_present<ConstantFPSDNode>(
       getSplatValue(DemandedElts, UndefElements));
 }
 
 ConstantFPSDNode *
 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
-  return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
+  return dyn_cast_if_present<ConstantFPSDNode>(getSplatValue(UndefElements));
 }
 
 int32_t
 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
                                                    uint32_t BitWidth) const {
   if (ConstantFPSDNode *CN =
-          dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
+          dyn_cast_if_present<ConstantFPSDNode>(getSplatValue(UndefElements))) {
     bool IsExact;
     APSInt IntVal(BitWidth);
     const APFloat &APF = CN->getValueAPF();
diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
index 12ed4a82ee91a5..b538f7e5908ecb 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
@@ -304,7 +304,7 @@ getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
 
 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
                                               const Twine &ErrMsg) {
-  const Instruction *I = dyn_cast_or_null<Instruction>(V);
+  const Instruction *I = dyn_cast_if_present<Instruction>(V);
   if (!V)
     return Ctx.emitError(ErrMsg);
 
@@ -3326,9 +3326,9 @@ void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
 
   // We may be able to ignore unreachable behind a noreturn call.
   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
-    if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
-      if (Call->doesNotReturn())
-        return;
+    if (const CallInst *Call = dyn_cast_if_present<CallInst>(I.getPrevNode())) {
+        if (Call->doesNotReturn())
+          return;
     }
   }
 
@@ -4124,7 +4124,7 @@ void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
       if (C && isa<VectorType>(C->getType()))
         C = C->getSplatValue();
 
-      const auto *CI = dyn_cast_or_null<ConstantInt>(C);
+      const auto *CI = dyn_cast_if_present<ConstantInt>(C);
       if (CI && CI->isZero())
         continue;
       if (CI && !ElementScalable) {
@@ -7162,7 +7162,8 @@ void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
     getUnderlyingObjects(ObjectPtr, Allocas);
 
     for (const Value *Alloca : Allocas) {
-      const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
+      const AllocaInst *LifetimeObject =
+          dyn_cast_if_present<AllocaInst>(Alloca);
 
       // Could not find an Alloca.
       if (!LifetimeObject)
@@ -9225,7 +9226,7 @@ class ExtraFlags {
 static bool isFunction(SDValue Op) {
   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
-      auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
+      auto Fn = dyn_cast_if_present<Function>(GA->getGlobal());
 
       // In normal "call dllimport func" instruction (non-inlineasm) it force
       // indirect access by specifing call opcode. And usually specially print
diff --git a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
index cf32350036d412..48938e90a8728a 100644
--- a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
@@ -545,7 +545,7 @@ lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
   SmallSet<SDValue, 8> LPadPointers;
   if (!UseRegistersForGCPointersInLandingPad)
     if (const auto *StInvoke =
-            dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
+            dyn_cast_if_present<InvokeInst>(SI.StatepointInstr)) {
       LandingPadInst *LPI = StInvoke->getLandingPadInst();
       for (const auto *Relocate : SI.GCRelocates)
         if (Relocate->getOperand(0) == LPI) {
diff --git a/llvm/lib/CodeGen/StackColoring.cpp b/llvm/lib/CodeGen/StackColoring.cpp
index 37f7aa9290054e..a9ef6de2483ae8 100644
--- a/llvm/lib/CodeGen/StackColoring.cpp
+++ b/llvm/lib/CodeGen/StackColoring.cpp
@@ -990,7 +990,7 @@ void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
       for (MachineMemOperand *MMO : I.memoperands()) {
         // We've replaced IR-level uses of the remapped allocas, so we only
         // need to replace direct uses here.
-        const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
+        const AllocaInst *AI = dyn_cast_if_present<AllocaInst>(MMO->getValue());
         if (!AI)
           continue;
 
@@ -1046,7 +1046,7 @@ void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
       for (MachineMemOperand *MMO : I.memoperands()) {
         // Collect MachineMemOperands which reference
         // FixedStackPseudoSourceValues with old frame indices.
-        if (const auto *FSV = dyn_cast_or_null<FixedStackPseudoSourceValue>(
+        if (const auto *FSV = dyn_cast_if_present<FixedStackPseudoSourceValue>(
                 MMO->getPseudoValue())) {
           int FI = FSV->getFrameIndex();
           auto To = SlotRemap.find(FI);
@@ -1069,7 +1069,7 @@ void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
                 // If this memory location comes from a known stack slot
                 // that is not remapped, we continue checking.
                 // Otherwise, we need to invalidate AA infomation.
-                const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(V);
+                const AllocaInst *AI = dyn_cast_if_present<AllocaInst>(V);
                 if (AI && MergedAllocas.count(AI)) {
                   MayHaveConflictingAAMD = true;
                   break;
diff --git a/llvm/lib/CodeGen/StackFrameLayoutAnalysisPass.cpp b/llvm/lib/CodeGen/StackFrameLayoutAnalysisPass.cpp
index 5d3903ed84ce82..86ea2b9524b1aa 100644
--- a/llvm/lib/CodeGen/StackFrameLayoutAnalysisPass.cpp
+++ b/llvm/lib/CodeGen/StackFrameLayoutAnalysisPass.cpp
@@ -220,7 +220,7 @@ struct StackFrameLayoutAnalysisPass : public MachineFunctionPass {
         for (MachineMemOperand *MO : MI.memoperands()) {
           if (!MO->isStore())
             continue;
-          auto *FI = dyn_cast_or_null<FixedStackPseudoSourceValue>(
+          auto *FI = dyn_cast_if_present<FixedStackPseudoSourceValue>(
               MO->getPseudoValue());
           if (!FI)
             continue;
diff --git a/llvm/lib/CodeGen/StackSlotColoring.cpp b/llvm/lib/CodeGen/StackSlotColoring.cpp
index c180f4d8f03655..bb6da31c428a57 100644
--- a/llvm/lib/CodeGen/StackSlotColoring.cpp
+++ b/llvm/lib/CodeGen/StackSlotColoring.cpp
@@ -219,8 +219,8 @@ void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
            MMOI != EE; ++MMOI) {
         MachineMemOperand *MMO = *MMOI;
         if (const FixedStackPseudoSourceValue *FSV =
-            dyn_cast_or_null<FixedStackPseudoSourceValue>(
-                MMO->getPseudoValue())) {
+                dyn_cast_if_present<FixedStackPseudoSourceValue>(
+                    MMO->getPseudoValue())) {
           int FI = FSV->getFrameIndex();
           if (FI >= 0)
             SSRefs[FI].push_back(MMO);
diff --git a/llvm/lib/CodeGen/TargetLoweringBase.cpp b/llvm/lib/CodeGen/TargetLoweringBase.cpp
index 2648c16bcd8d90..91190b156309b1 100644
--- a/llvm/lib/CodeGen/TargetLoweringBase.cpp
+++ b/llvm/lib/CodeGen/TargetLoweringBase.cpp
@@ -1908,7 +1908,7 @@ TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
   auto UnsafeStackPtr =
-      dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
+      dyn_cast_if_present<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
 
   Type *StackPtrTy = PointerType::getUnqual(M->getContext());
 
@@ -1999,7 +1999,7 @@ Value *TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB) const {
     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
     PointerType *PtrTy = PointerType::getUnqual(M.getContext());
     Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy);
-    if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C))
+    if (GlobalVariable *G = dyn_cast_if_present<GlobalVariable>(C))
       G->setVisibility(GlobalValue::HiddenVisibility);
     return C;
   }
diff --git a/llvm/lib/CodeGen/WinEHPrepare.cpp b/llvm/lib/CodeGen/WinEHPrepare.cpp
index 95976c218c2f14..e7420a4b2da024 100644
--- a/llvm/lib/CodeGen/WinEHPrepare.cpp
+++ b/llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -1095,8 +1095,8 @@ void WinEHPrepareImpl::removeImplausibleInstructions(Function &F) {
     std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
     auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
-    auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
-    auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
+    auto *CatchPad = dyn_cast_if_present<CatchPadInst>(FuncletPad);
+    auto *CleanupPad = dyn_cast_if_present<CleanupPadInst>(FuncletPad);
 
     for (BasicBlock *BB : BlocksInFunclet) {
       for (Instruction &I : *BB) {
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
index c671aedbc9e52b..c6b47bbdca2ec4 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
@@ -1341,7 +1341,7 @@ DWARFTypeUnit *DWARFContext::getTypeUnitForHash(uint16_t Version, uint64_t Hash,
   DWARFUnitVector &DWOUnits = State->getDWOUnits();
   if (const auto &TUI = getTUIndex()) {
     if (const auto *R = TUI.getFromHash(Hash))
-      return dyn_cast_or_null<DWARFTypeUnit>(
+      return dyn_cast_if_present<DWARFTypeUnit>(
           DWOUnits.getUnitForIndexEntry(*R));
     return nullptr;
   }
@@ -1357,7 +1357,7 @@ DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
 
   if (const auto &CUI = getCUIndex()) {
     if (const auto *R = CUI.getFromHash(Hash))
-      return dyn_cast_or_null<DWARFCompileUnit>(
+      return dyn_cast_if_present<DWARFCompileUnit>(
           DWOUnits.getUnitForIndexEntry(*R));
     return nullptr;
   }
@@ -1505,7 +1505,7 @@ DWARFUnitVector &DWARFContext::getDWOUnits(bool Lazy) {
 }
 
 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
-  return dyn_cast_or_null<DWARFCompileUnit>(
+  return dyn_cast_if_present<DWARFCompileUnit>(
       State->getNormalUnits().getUnitForOffset(Offset));
 }
 
diff --git a/llvm/lib/DebugInfo/PDB/PDBContext.cpp b/llvm/lib/DebugInfo/PDB/PDBContext.cpp
index e600fb7385f133..d77e5631a10947 100644
--- a/llvm/lib/DebugInfo/PDB/PDBContext.cpp
+++ b/llvm/lib/DebugInfo/PDB/PDBContext.cpp
@@ -40,9 +40,9 @@ DILineInfo PDBContext::getLineInfoForAddress(object::SectionedAddress Address,
   uint32_t Length = 1;
   std::unique_ptr<PDBSymbol> Symbol =
       Session->findSymbolByAddress(Address.Address, PDB_SymType::None);
-  if (auto Func = dyn_cast_or_null<PDBSymbolFunc>(Symbol.get())) {
+  if (auto Func = dyn_cast_if_present<PDBSymbolFunc>(Symbol.get())) {
     Length = Func->getLength();
-  } else if (auto Data = dyn_cast_or_null<PDBSymbolData>(Symbol.get())) {
+  } else if (auto Data = dyn_cast_if_present<PDBSymbolData>(Symbol.get())) {
     Length = Data->getLength();
   }
 
@@ -147,7 +147,7 @@ std::string PDBContext::getFunctionName(uint64_t Address,
 
   std::unique_ptr<PDBSymbol> FuncSymbol =
       Session->findSymbolByAddress(Address, PDB_SymType::Function);
-  auto *Func = dyn_cast_or_null<PDBSymbolFunc>(FuncSymbol.get());
+  auto *Func = dyn_cast_if_present<PDBSymbolFunc>(FuncSymbol.get());
 
   if (NameKind == DINameKind::LinkageName) {
     // It is not possible to get the mangled linkage name through a
@@ -155,7 +155,8 @@ std::string PDBContext::getFunctionName(uint64_t Address,
     // PDBSymbolPublicSymbol.
     auto PublicSym =
         Session->findSymbolByAddress(Address, PDB_SymType::PublicSymbol);
-    if (auto *PS = dyn_cast_or_null<PDBSymbolPublicSymbol>(PublicSym.get())) {
+    if (auto *PS =
+            dyn_cast_if_present<PDBSymbolPublicSymbol>(PublicSym.get())) {
       // If we also have a function symbol, prefer the use of public symbol name
       // only if it refers to the same address. The public symbol uses the
       // linkage name while the function does not.
diff --git a/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp b/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp
index 1373615522eb24..46dbc211218594 100644
--- a/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp
+++ b/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp
@@ -82,7 +82,8 @@ bool PDBSymbolTypeFunctionSig::isCVarArgs() const {
   if (NumArgs == 0)
     return false;
   auto Last = SigArguments->getChildAtIndex(NumArgs - 1);
-  if (auto Builtin = llvm::dyn_cast_or_null<PDBSymbolTypeBuiltin>(Last.get())) {
+  if (auto Builtin =
+          llvm::dyn_cast_if_present<PDBSymbolTypeBuiltin>(Last.get())) {
     if (Builtin->getBuiltinType() == PDB_BuiltinType::None)
       return true;
   }
diff --git a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp
index 43e5c9e9329e00..de9c76a015b2b8 100644
--- a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp
+++ b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp
@@ -557,7 +557,8 @@ LLVMSymbolizer::getOrCreateObject(const std::string &Path,
   if (!Bin)
     return static_cast<ObjectFile *>(nullptr);
 
-  if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
+  if (MachOUniversalBinary *UB =
+          dyn_cast_if_present<MachOUniversalBinary>(Bin)) {
     auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
     if (I != ObjectForUBPathAndArch.end())
       return I->second.get();
diff --git a/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp b/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp
index 8d5608cc4d4cfd..3536b4382a6f11 100644
--- a/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp
@@ -24,10 +24,9 @@ namespace llvm {
 namespace orc {
 
 CtorDtorIterator::CtorDtorIterator(const GlobalVariable *GV, bool End)
-  : InitList(
-      GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
-    I((InitList && End) ? InitList->getNumOperands() : 0) {
-}
+    : InitList(GV ? dyn_cast_if_present<ConstantArray>(GV->getInitializer())
+                  : nullptr),
+      I((InitList && End) ? InitList->getNumOperands() : 0) {}
 
 bool CtorDtorIterator::operator==(const CtorDtorIterator &Other) const {
   assert(InitList == Other.InitList && "Incomparable iterators.");
@@ -58,10 +57,10 @@ CtorDtorIterator::Element CtorDtorIterator::operator*() const {
 
   // Extract function pointer, pulling off any casts.
   while (FuncC) {
-    if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
+    if (Function *F = dyn_cast_if_present<Function>(FuncC)) {
       Func = F;
       break;
-    } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
+    } else if (ConstantExpr *CE = dyn_cast_if_present<ConstantExpr>(FuncC)) {
       if (CE->isCast())
         FuncC = CE->getOperand(0);
       else
diff --git a/llvm/lib/IR/AsmWriter.cpp b/llvm/lib/IR/AsmWriter.cpp
index 95cdec722062e3..c853b658330b57 100644
--- a/llvm/lib/IR/AsmWriter.cpp
+++ b/llvm/lib/IR/AsmWriter.cpp
@@ -1137,7 +1137,7 @@ void SlotTracker::processInstructionMetadata(const Instruction &I) {
     if (Function *F = CI->getCalledFunction())
       if (F->isIntrinsic())
         for (auto &Op : I.operands())
-          if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
+          if (auto *V = dyn_cast_if_present<MetadataAsValue>(Op))
             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
               CreateMetadataSlot(N);
 
@@ -1295,7 +1295,7 @@ void SlotTracker::CreateMetadataSlot(const MDNode *N) {
 
   // Recursively add any MDNodes referenced by operands.
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
-    if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
+    if (const MDNode *Op = dyn_cast_if_present<MDNode>(N->getOperand(i)))
       CreateMetadataSlot(Op);
 }
 
@@ -1932,7 +1932,7 @@ static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
   MDFieldPrinter Printer(Out, WriterCtx);
 
   auto *Count = N->getRawCountNode();
-  if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
+  if (auto *CE = dyn_cast_if_present<ConstantAsMetadata>(Count)) {
     auto *CV = cast<ConstantInt>(CE->getValue());
     Printer.printInt("count", CV->getSExtValue(),
                      /* ShouldSkipZero */ false);
@@ -1942,7 +1942,7 @@ static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
   // A lowerBound of constant 0 should not be skipped, since it is different
   // from an unspecified lower bound (= nullptr).
   auto *LBound = N->getRawLowerBound();
-  if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
+  if (auto *LE = dyn_cast_if_present<ConstantAsMetadata>(LBound)) {
     auto *LV = cast<ConstantInt>(LE->getValue());
     Printer.printInt("lowerBound", LV->getSExtValue(),
                      /* ShouldSkipZero */ false);
@@ -1950,7 +1950,7 @@ static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
 
   auto *UBound = N->getRawUpperBound();
-  if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
+  if (auto *UE = dyn_cast_if_present<ConstantAsMetadata>(UBound)) {
     auto *UV = cast<ConstantInt>(UE->getValue());
     Printer.printInt("upperBound", UV->getSExtValue(),
                      /* ShouldSkipZero */ false);
@@ -1958,7 +1958,7 @@ static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
 
   auto *Stride = N->getRawStride();
-  if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
+  if (auto *SE = dyn_cast_if_present<ConstantAsMetadata>(Stride)) {
     auto *SV = cast<ConstantInt>(SE->getValue());
     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
   } else
@@ -1973,7 +1973,7 @@ static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
   MDFieldPrinter Printer(Out, WriterCtx);
 
   auto IsConstant = [&](Metadata *Bound) -> bool {
-    if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
+    if (auto *BE = dyn_cast_if_present<DIExpression>(Bound)) {
       return BE->isConstant() &&
              DIExpression::SignedOrUnsignedConstant::SignedConstant ==
                  *BE->isConstant();
@@ -1983,7 +1983,7 @@ static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
 
   auto GetConstant = [&](Metadata *Bound) -> int64_t {
     assert(IsConstant(Bound) && "Expected constant");
-    auto *BE = dyn_cast_or_null<DIExpression>(Bound);
+    auto *BE = dyn_cast_if_present<DIExpression>(Bound);
     return static_cast<int64_t>(BE->getElement(1));
   };
 
@@ -4801,7 +4801,7 @@ static bool isReferencingMDNode(const Instruction &I) {
     if (Function *F = CI->getCalledFunction())
       if (F->isIntrinsic())
         for (auto &Op : I.operands())
-          if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
+          if (auto *V = dyn_cast_if_present<MetadataAsValue>(Op))
             if (isa<MDNode>(V->getMetadata()))
               return true;
   return false;
diff --git a/llvm/lib/IR/AutoUpgrade.cpp b/llvm/lib/IR/AutoUpgrade.cpp
index 6b54047020a05d..dfbbd92d3de4cb 100644
--- a/llvm/lib/IR/AutoUpgrade.cpp
+++ b/llvm/lib/IR/AutoUpgrade.cpp
@@ -4370,7 +4370,7 @@ void llvm::UpgradeIntrinsicCall(CallBase *CI, Function *NewFn) {
     // Upgrade from the old version that had an extra offset argument.
     assert(CI->arg_size() == 4);
     // Drop nonzero offsets instead of attempting to upgrade them.
-    if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
+    if (auto *Offset = dyn_cast_if_present<Constant>(CI->getArgOperand(1)))
       if (Offset->isZeroValue()) {
         NewCall = Builder.CreateCall(
             NewFn,
@@ -4774,7 +4774,7 @@ static bool UpgradeRetainReleaseMarker(Module &M) {
   if (ModRetainReleaseMarker) {
     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
     if (Op) {
-      MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
+      MDString *ID = dyn_cast_if_present<MDString>(Op->getOperand(0));
       if (ID) {
         SmallVector<StringRef, 4> ValueComp;
         ID->getString().split(ValueComp, "#");
@@ -4928,7 +4928,7 @@ bool llvm::UpgradeModuleFlags(Module &M) {
     MDNode *Op = ModFlags->getOperand(I);
     if (Op->getNumOperands() != 3)
       continue;
-    MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
+    MDString *ID = dyn_cast_if_present<MDString>(Op->getOperand(1));
     if (!ID)
       continue;
     auto SetBehavior = [&](Module::ModFlagBehavior B) {
@@ -4981,7 +4981,7 @@ bool llvm::UpgradeModuleFlags(Module &M) {
     // section name so that llvm-lto will not complain about mismatching
     // module flags that is functionally the same.
     if (ID->getString() == "Objective-C Image Info Section") {
-      if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
+      if (auto *Value = dyn_cast_if_present<MDString>(Op->getOperand(2))) {
         SmallVector<StringRef, 4> ValueComp;
         Value->getString().split(ValueComp, " ");
         if (ValueComp.size() != 1) {
@@ -5118,12 +5118,12 @@ void llvm::UpgradeFunctionAttributes(Function &F) {
 }
 
 static bool isOldLoopArgument(Metadata *MD) {
-  auto *T = dyn_cast_or_null<MDTuple>(MD);
+  auto *T = dyn_cast_if_present<MDTuple>(MD);
   if (!T)
     return false;
   if (T->getNumOperands() < 1)
     return false;
-  auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
+  auto *S = dyn_cast_if_present<MDString>(T->getOperand(0));
   if (!S)
     return false;
   return S->getString().starts_with("llvm.vectorizer.");
@@ -5142,12 +5142,12 @@ static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
 }
 
 static Metadata *upgradeLoopArgument(Metadata *MD) {
-  auto *T = dyn_cast_or_null<MDTuple>(MD);
+  auto *T = dyn_cast_if_present<MDTuple>(MD);
   if (!T)
     return MD;
   if (T->getNumOperands() < 1)
     return MD;
-  auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
+  auto *OldTag = dyn_cast_if_present<MDString>(T->getOperand(0));
   if (!OldTag)
     return MD;
   if (!OldTag->getString().starts_with("llvm.vectorizer."))
diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 03b74b0480f071..28dff1b02d9245 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -370,7 +370,7 @@ const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
   if (!RI || RI == &InstList.front())
     return nullptr;
 
-  if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
+  if (auto *CI = dyn_cast_if_present<CallInst>(RI->getPrevNode()))
     if (Function *F = CI->getCalledFunction())
       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
         return CI;
diff --git a/llvm/lib/IR/ConstantFold.cpp b/llvm/lib/IR/ConstantFold.cpp
index d499d74f7ba010..b4cbc6f179752f 100644
--- a/llvm/lib/IR/ConstantFold.cpp
+++ b/llvm/lib/IR/ConstantFold.cpp
@@ -1456,7 +1456,7 @@ static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
       return false;
   } else {
     auto *CV = cast<ConstantDataVector>(Idxs[0]);
-    CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
+    CI = dyn_cast_if_present<ConstantInt>(CV->getSplatValue());
     if (!CI || !CI->isOne())
       return false;
   }
diff --git a/llvm/lib/IR/Constants.cpp b/llvm/lib/IR/Constants.cpp
index a38b912164b130..7ffdf0d7ae7f29 100644
--- a/llvm/lib/IR/Constants.cpp
+++ b/llvm/lib/IR/Constants.cpp
@@ -46,7 +46,7 @@ bool Constant::isNegativeZeroValue() const {
 
   // Equivalent for a vector of -0.0's.
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->isNegativeZeroValue();
 
   // We've already handled true FP case; any other FP vectors can't represent -0.0.
@@ -66,7 +66,7 @@ bool Constant::isZeroValue() const {
 
   // Check for constant splat vectors of 1 values.
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->isZero();
 
   // Otherwise, just use +0.0.
@@ -203,7 +203,7 @@ bool Constant::isFiniteNonZeroFP() const {
 
   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
-      auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
+      auto *CFP = dyn_cast_if_present<ConstantFP>(getAggregateElement(I));
       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
         return false;
     }
@@ -211,7 +211,7 @@ bool Constant::isFiniteNonZeroFP() const {
   }
 
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->isFiniteNonZeroFP();
 
   // It *may* contain finite non-zero, we can't tell.
@@ -224,7 +224,7 @@ bool Constant::isNormalFP() const {
 
   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
-      auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
+      auto *CFP = dyn_cast_if_present<ConstantFP>(getAggregateElement(I));
       if (!CFP || !CFP->getValueAPF().isNormal())
         return false;
     }
@@ -232,7 +232,7 @@ bool Constant::isNormalFP() const {
   }
 
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->isNormalFP();
 
   // It *may* contain a normal fp value, we can't tell.
@@ -245,7 +245,7 @@ bool Constant::hasExactInverseFP() const {
 
   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
-      auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
+      auto *CFP = dyn_cast_if_present<ConstantFP>(getAggregateElement(I));
       if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
         return false;
     }
@@ -253,7 +253,7 @@ bool Constant::hasExactInverseFP() const {
   }
 
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->hasExactInverseFP();
 
   // It *may* have an exact inverse fp value, we can't tell.
@@ -266,7 +266,7 @@ bool Constant::isNaN() const {
 
   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
-      auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
+      auto *CFP = dyn_cast_if_present<ConstantFP>(getAggregateElement(I));
       if (!CFP || !CFP->isNaN())
         return false;
     }
@@ -274,7 +274,7 @@ bool Constant::isNaN() const {
   }
 
   if (getType()->isVectorTy())
-    if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
+    if (const auto *SplatCFP = dyn_cast_if_present<ConstantFP>(getSplatValue()))
       return SplatCFP->isNaN();
 
   // It *may* be NaN, we can't tell.
diff --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp
index fb30fbce0ba22e..862207eeae69d5 100644
--- a/llvm/lib/IR/Core.cpp
+++ b/llvm/lib/IR/Core.cpp
@@ -1053,15 +1053,15 @@ LLVMInstructionGetAllMetadataOtherThanDebugLoc(LLVMValueRef Value,
 
 /*--.. Conversion functions ................................................--*/
 
-#define LLVM_DEFINE_VALUE_CAST(name)                                       \
-  LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                           \
-    return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \
+#define LLVM_DEFINE_VALUE_CAST(name)                                           \
+  LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                               \
+    return wrap(static_cast<Value *>(dyn_cast_if_present<name>(unwrap(Val)))); \
   }
 
 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)
 
 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {
-  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
+  if (auto *MD = dyn_cast_if_present<MetadataAsValue>(unwrap(Val)))
     if (isa<MDNode>(MD->getMetadata()) ||
         isa<ValueAsMetadata>(MD->getMetadata()))
       return Val;
@@ -1069,14 +1069,14 @@ LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {
 }
 
 LLVMValueRef LLVMIsAValueAsMetadata(LLVMValueRef Val) {
-  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
+  if (auto *MD = dyn_cast_if_present<MetadataAsValue>(unwrap(Val)))
     if (isa<ValueAsMetadata>(MD->getMetadata()))
       return Val;
   return nullptr;
 }
 
 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) {
-  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))
+  if (auto *MD = dyn_cast_if_present<MetadataAsValue>(unwrap(Val)))
     if (isa<MDString>(MD->getMetadata()))
       return Val;
   return nullptr;
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 62efaba025344b..b4e017bc48254e 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -717,7 +717,7 @@ DIGenericSubrange *DIBuilder::getOrCreateGenericSubrange(
 static void checkGlobalVariableScope(DIScope *Context) {
 #ifndef NDEBUG
   if (auto *CT =
-          dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
+          dyn_cast_if_present<DICompositeType>(getNonCompileUnitScope(Context)))
     assert(CT->getIdentifier().empty() &&
            "Context of a global variable should not be a type with identifier");
 #endif
@@ -1115,7 +1115,7 @@ void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) {
   // cycles underneath it.
   if (T->isResolved())
     for (const MDOperand &O : T->operands())
-      if (auto *N = dyn_cast_or_null<MDNode>(O))
+      if (auto *N = dyn_cast_if_present<MDNode>(O))
         trackIfUnresolved(N);
 }
 
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index eab05eed428e47..6373c2bc751749 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -116,7 +116,7 @@ void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
 }
 
 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
-  if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
+  if (auto *LocalScope = dyn_cast_if_present<DILocalScope>(Scope))
     return LocalScope->getSubprogram();
   return nullptr;
 }
@@ -386,7 +386,7 @@ void llvm::updateLoopMetadataDebugLocations(
 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
                                   SmallPtrSetImpl<Metadata *> &Reachable,
                                   Metadata *MD) {
-  MDNode *N = dyn_cast_or_null<MDNode>(MD);
+  MDNode *N = dyn_cast_if_present<MDNode>(MD);
   if (!N)
     return false;
   if (isa<DILocation>(N) || Reachable.count(N))
@@ -408,7 +408,7 @@ static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited,
                             SmallPtrSetImpl<Metadata *> &AllDILocation,
                             const SmallPtrSetImpl<Metadata *> &DIReachable,
                             Metadata *MD) {
-  MDNode *N = dyn_cast_or_null<MDNode>(MD);
+  MDNode *N = dyn_cast_if_present<MDNode>(MD);
   if (!N)
     return false;
   if (isa<DILocation>(N) || AllDILocation.count(N))
@@ -438,7 +438,7 @@ stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation,
   if (!DIReachable.count(MD))
     return MD;
 
-  MDNode *N = dyn_cast_or_null<MDNode>(MD);
+  MDNode *N = dyn_cast_if_present<MDNode>(MD);
   if (!N)
     return MD;
 
@@ -605,7 +605,7 @@ class DebugTypeInfoRemoval {
 
     return M;
   }
-  MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
+  MDNode *mapNode(Metadata *N) { return dyn_cast_if_present<MDNode>(map(N)); }
 
   /// Recursively remap N and all its referenced children. Does a DF post-order
   /// traversal, so as to remap bottoms up.
@@ -769,7 +769,7 @@ void DebugTypeInfoRemoval::traverse(MDNode *N) {
       continue;
     }
     for (auto &I : N->operands())
-      if (auto *MDN = dyn_cast_or_null<MDNode>(I))
+      if (auto *MDN = dyn_cast_if_present<MDNode>(I))
         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
             !isa<DICompileUnit>(MDN))
           ToVisit.push_back(MDN);
@@ -842,7 +842,7 @@ bool llvm::stripNonLineTableDebugInfo(Module &M) {
 
         // Remap DILocations in llvm.loop attachments.
         updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
-          if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
+          if (auto *Loc = dyn_cast_if_present<DILocation>(MD))
             return remapDebugLoc(Loc).get();
           return MD;
         });
diff --git a/llvm/lib/IR/DebugInfoMetadata.cpp b/llvm/lib/IR/DebugInfoMetadata.cpp
index 51950fc937f0ab..c2c11e180755c1 100644
--- a/llvm/lib/IR/DebugInfoMetadata.cpp
+++ b/llvm/lib/IR/DebugInfoMetadata.cpp
@@ -705,7 +705,7 @@ DIType *DIDerivedType::getClassType() const {
 uint32_t DIDerivedType::getVBPtrOffset() const {
   assert(getTag() == dwarf::DW_TAG_inheritance);
   if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
-    if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
+    if (auto *CI = dyn_cast_if_present<ConstantInt>(CM->getValue()))
       return static_cast<uint32_t>(CI->getZExtValue());
   return 0;
 }
diff --git a/llvm/lib/IR/LLVMContextImpl.h b/llvm/lib/IR/LLVMContextImpl.h
index 6a20291344989d..d764983aeb95e8 100644
--- a/llvm/lib/IR/LLVMContextImpl.h
+++ b/llvm/lib/IR/LLVMContextImpl.h
@@ -378,8 +378,8 @@ template <> struct MDNodeKeyImpl<DISubrange> {
       if (Node1 == Node2)
         return true;
 
-      ConstantAsMetadata *MD1 = dyn_cast_or_null<ConstantAsMetadata>(Node1);
-      ConstantAsMetadata *MD2 = dyn_cast_or_null<ConstantAsMetadata>(Node2);
+      ConstantAsMetadata *MD1 = dyn_cast_if_present<ConstantAsMetadata>(Node1);
+      ConstantAsMetadata *MD2 = dyn_cast_if_present<ConstantAsMetadata>(Node2);
       if (MD1 && MD2) {
         ConstantInt *CV1 = cast<ConstantInt>(MD1->getValue());
         ConstantInt *CV2 = cast<ConstantInt>(MD2->getValue());
@@ -426,7 +426,7 @@ template <> struct MDNodeKeyImpl<DIGenericSubrange> {
   }
 
   unsigned getHashValue() const {
-    auto *MD = dyn_cast_or_null<ConstantAsMetadata>(CountNode);
+    auto *MD = dyn_cast_if_present<ConstantAsMetadata>(CountNode);
     if (CountNode && MD)
       return hash_combine(cast<ConstantInt>(MD->getValue())->getSExtValue(),
                           LowerBound, UpperBound, Stride);
@@ -577,7 +577,7 @@ template <> struct MDNodeKeyImpl<DIDerivedType> {
     // Otherwise the hash will be stronger than
     // MDNodeSubsetEqualImpl::isODRMember().
     if (Tag == dwarf::DW_TAG_member && Name)
-      if (auto *CT = dyn_cast_or_null<DICompositeType>(Scope))
+      if (auto *CT = dyn_cast_if_present<DICompositeType>(Scope))
         if (CT->getRawIdentifier())
           return hash_combine(Name, Scope);
 
@@ -610,7 +610,7 @@ template <> struct MDNodeSubsetEqualImpl<DIDerivedType> {
     if (Tag != dwarf::DW_TAG_member || !Name)
       return false;
 
-    auto *CT = dyn_cast_or_null<DICompositeType>(Scope);
+    auto *CT = dyn_cast_if_present<DICompositeType>(Scope);
     if (!CT || !CT->getRawIdentifier())
       return false;
 
@@ -823,7 +823,7 @@ template <> struct MDNodeKeyImpl<DISubprogram> {
     // name.  Otherwise the hash will be stronger than
     // MDNodeSubsetEqualImpl::isDeclarationOfODRMember().
     if (!isDefinition() && LinkageName)
-      if (auto *CT = dyn_cast_or_null<DICompositeType>(Scope))
+      if (auto *CT = dyn_cast_if_present<DICompositeType>(Scope))
         if (CT->getRawIdentifier())
           return hash_combine(LinkageName, Scope);
 
@@ -859,7 +859,7 @@ template <> struct MDNodeSubsetEqualImpl<DISubprogram> {
     if (IsDefinition || !Scope || !LinkageName)
       return false;
 
-    auto *CT = dyn_cast_or_null<DICompositeType>(Scope);
+    auto *CT = dyn_cast_if_present<DICompositeType>(Scope);
     if (!CT || !CT->getRawIdentifier())
       return false;
 
diff --git a/llvm/lib/IR/Mangler.cpp b/llvm/lib/IR/Mangler.cpp
index 3acac2c3e3db16..3cd7a498bdeb3a 100644
--- a/llvm/lib/IR/Mangler.cpp
+++ b/llvm/lib/IR/Mangler.cpp
@@ -145,7 +145,8 @@ void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
 
   // Mangle functions with Microsoft calling conventions specially.  Only do
   // this mangling for x86_64 vectorcall and 32-bit x86.
-  const Function *MSFunc = dyn_cast_or_null<Function>(GV->getAliaseeObject());
+  const Function *MSFunc =
+      dyn_cast_if_present<Function>(GV->getAliaseeObject());
 
   // Don't add byte count suffixes when '\01' or '?' are in the first
   // character.
diff --git a/llvm/lib/IR/Metadata.cpp b/llvm/lib/IR/Metadata.cpp
index 7bc25e30b89327..8262b44caccac7 100644
--- a/llvm/lib/IR/Metadata.cpp
+++ b/llvm/lib/IR/Metadata.cpp
@@ -708,7 +708,7 @@ void MDNode::Header::resizeSmallToLarge(size_t NumOps) {
 }
 
 static bool isOperandUnresolved(Metadata *Op) {
-  if (auto *N = dyn_cast_or_null<MDNode>(Op))
+  if (auto *N = dyn_cast_if_present<MDNode>(Op))
     return !N->isResolved();
   return false;
 }
@@ -805,7 +805,7 @@ void MDNode::resolveCycles() {
 
   // Resolve all operands.
   for (const auto &Op : operands()) {
-    auto *N = dyn_cast_or_null<MDNode>(Op);
+    auto *N = dyn_cast_if_present<MDNode>(Op);
     if (!N)
       continue;
 
@@ -1058,7 +1058,7 @@ void MDNode::setOperand(unsigned I, Metadata *New) {
 static MDNode *getOrSelfReference(LLVMContext &Context,
                                   ArrayRef<Metadata *> Ops) {
   if (!Ops.empty())
-    if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
+    if (MDNode *N = dyn_cast_if_present<MDNode>(Ops[0]))
       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
           if (Ops[I] != N->getOperand(I))
diff --git a/llvm/lib/IR/Module.cpp b/llvm/lib/IR/Module.cpp
index eeb90a6cb3c465..cb5b3a7b18f66c 100644
--- a/llvm/lib/IR/Module.cpp
+++ b/llvm/lib/IR/Module.cpp
@@ -168,7 +168,7 @@ FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
 // If it does not exist, return null.
 //
 Function *Module::getFunction(StringRef Name) const {
-  return dyn_cast_or_null<Function>(getNamedValue(Name));
+  return dyn_cast_if_present<Function>(getNamedValue(Name));
 }
 
 //===----------------------------------------------------------------------===//
@@ -185,7 +185,7 @@ Function *Module::getFunction(StringRef Name) const {
 GlobalVariable *Module::getGlobalVariable(StringRef Name,
                                           bool AllowLocal) const {
   if (GlobalVariable *Result =
-      dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
+          dyn_cast_if_present<GlobalVariable>(getNamedValue(Name)))
     if (AllowLocal || !Result->hasLocalLinkage())
       return Result;
   return nullptr;
@@ -201,7 +201,7 @@ Constant *Module::getOrInsertGlobal(
     StringRef Name, Type *Ty,
     function_ref<GlobalVariable *()> CreateGlobalCallback) {
   // See if we have a definition for the specified global already.
-  GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
+  GlobalVariable *GV = dyn_cast_if_present<GlobalVariable>(getNamedValue(Name));
   if (!GV)
     GV = CreateGlobalCallback();
   assert(GV && "The CreateGlobalCallback is expected to create a global");
@@ -226,11 +226,11 @@ Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
 // If it does not exist, return null.
 //
 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
-  return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
+  return dyn_cast_if_present<GlobalAlias>(getNamedValue(Name));
 }
 
 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
-  return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
+  return dyn_cast_if_present<GlobalIFunc>(getNamedValue(Name));
 }
 
 /// getNamedMetadata - Return the first NamedMDNode in the module with the
@@ -279,7 +279,7 @@ bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
     return false;
   if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
     return false;
-  MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
+  MDString *K = dyn_cast_if_present<MDString>(ModFlag.getOperand(1));
   if (!K)
     return false;
   Key = K;
@@ -709,7 +709,7 @@ void Module::setFramePointer(FramePointerKind Kind) {
 
 StringRef Module::getStackProtectorGuard() const {
   Metadata *MD = getModuleFlag("stack-protector-guard");
-  if (auto *MDS = dyn_cast_or_null<MDString>(MD))
+  if (auto *MDS = dyn_cast_if_present<MDString>(MD))
     return MDS->getString();
   return {};
 }
@@ -721,7 +721,7 @@ void Module::setStackProtectorGuard(StringRef Kind) {
 
 StringRef Module::getStackProtectorGuardReg() const {
   Metadata *MD = getModuleFlag("stack-protector-guard-reg");
-  if (auto *MDS = dyn_cast_or_null<MDString>(MD))
+  if (auto *MDS = dyn_cast_if_present<MDString>(MD))
     return MDS->getString();
   return {};
 }
@@ -733,7 +733,7 @@ void Module::setStackProtectorGuardReg(StringRef Reg) {
 
 StringRef Module::getStackProtectorGuardSymbol() const {
   Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
-  if (auto *MDS = dyn_cast_or_null<MDString>(MD))
+  if (auto *MDS = dyn_cast_if_present<MDString>(MD))
     return MDS->getString();
   return {};
 }
@@ -791,10 +791,10 @@ void Module::setSDKVersion(const VersionTuple &V) {
 }
 
 static VersionTuple getSDKVersionMD(Metadata *MD) {
-  auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
+  auto *CM = dyn_cast_if_present<ConstantAsMetadata>(MD);
   if (!CM)
     return {};
-  auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
+  auto *Arr = dyn_cast_if_present<ConstantDataArray>(CM->getValue());
   if (!Arr)
     return {};
   auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
diff --git a/llvm/lib/IR/ModuleSummaryIndex.cpp b/llvm/lib/IR/ModuleSummaryIndex.cpp
index 198c730418c724..792669b74a332a 100644
--- a/llvm/lib/IR/ModuleSummaryIndex.cpp
+++ b/llvm/lib/IR/ModuleSummaryIndex.cpp
@@ -166,7 +166,7 @@ void ModuleSummaryIndex::collectDefinedFunctionsForModule(
   for (auto &GlobalList : *this) {
     auto GUID = GlobalList.first;
     for (auto &GlobSummary : GlobalList.second.SummaryList) {
-      auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
+      auto *Summary = dyn_cast_if_present<FunctionSummary>(GlobSummary.get());
       if (!Summary)
         // Ignore global variable, focus on functions
         continue;
@@ -481,7 +481,7 @@ static std::string fflagsToString(FunctionSummary::FFlags F) {
 
 // Get string representation of function instruction count and flags.
 static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
-  auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
+  auto *FS = dyn_cast_if_present<FunctionSummary>(GVS);
   if (!FS)
     return "";
 
@@ -665,12 +665,12 @@ void ModuleSummaryIndex::exportToDot(
         Draw(SummaryIt.first, R.getGUID(),
              R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
 
-      if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
+      if (auto *AS = dyn_cast_if_present<AliasSummary>(SummaryIt.second)) {
         Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
         continue;
       }
 
-      if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
+      if (auto *FS = dyn_cast_if_present<FunctionSummary>(SummaryIt.second))
         for (auto &CGEdge : FS->calls())
           Draw(SummaryIt.first, CGEdge.first.getGUID(),
                static_cast<int>(CGEdge.second.Hotness));
diff --git a/llvm/lib/IR/ProfileSummary.cpp b/llvm/lib/IR/ProfileSummary.cpp
index 9f7335ecbe44d7..9abf20433ba131 100644
--- a/llvm/lib/IR/ProfileSummary.cpp
+++ b/llvm/lib/IR/ProfileSummary.cpp
@@ -192,21 +192,21 @@ static bool getOptionalVal(MDTuple *Tuple, unsigned &Idx, const char *Key,
 }
 
 ProfileSummary *ProfileSummary::getFromMD(Metadata *MD) {
-  MDTuple *Tuple = dyn_cast_or_null<MDTuple>(MD);
+  MDTuple *Tuple = dyn_cast_if_present<MDTuple>(MD);
   if (!Tuple || Tuple->getNumOperands() < 8 || Tuple->getNumOperands() > 10)
     return nullptr;
 
   unsigned I = 0;
   auto &FormatMD = Tuple->getOperand(I++);
   ProfileSummary::Kind SummaryKind;
-  if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
+  if (isKeyValuePair(dyn_cast_if_present<MDTuple>(FormatMD), "ProfileFormat",
                      "SampleProfile"))
     SummaryKind = PSK_Sample;
-  else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
-                          "InstrProf"))
+  else if (isKeyValuePair(dyn_cast_if_present<MDTuple>(FormatMD),
+                          "ProfileFormat", "InstrProf"))
     SummaryKind = PSK_Instr;
-  else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
-                          "CSInstrProf"))
+  else if (isKeyValuePair(dyn_cast_if_present<MDTuple>(FormatMD),
+                          "ProfileFormat", "CSInstrProf"))
     SummaryKind = PSK_CSInstr;
   else
     return nullptr;
diff --git a/llvm/lib/IR/Type.cpp b/llvm/lib/IR/Type.cpp
index 85d779c98a9b14..c00dd8c771d4ee 100644
--- a/llvm/lib/IR/Type.cpp
+++ b/llvm/lib/IR/Type.cpp
@@ -625,7 +625,7 @@ bool StructType::indexValid(const Value *V) const {
   const Constant *C = dyn_cast<Constant>(V);
   if (C && V->getType()->isVectorTy())
     C = C->getSplatValue();
-  const ConstantInt *CU = dyn_cast_or_null<ConstantInt>(C);
+  const ConstantInt *CU = dyn_cast_if_present<ConstantInt>(C);
   return CU && CU->getZExtValue() < getNumElements();
 }
 
diff --git a/llvm/lib/IR/User.cpp b/llvm/lib/IR/User.cpp
index 637af7aaa24530..8e05259d4f3ab8 100644
--- a/llvm/lib/IR/User.cpp
+++ b/llvm/lib/IR/User.cpp
@@ -33,7 +33,7 @@ bool User::replaceUsesOfWith(Value *From, Value *To) {
       setOperand(i, To);
       Changed = true;
     }
-  if (auto DVI = dyn_cast_or_null<DbgVariableIntrinsic>(this)) {
+  if (auto DVI = dyn_cast_if_present<DbgVariableIntrinsic>(this)) {
     if (is_contained(DVI->location_ops(), From)) {
       DVI->replaceVariableLocationOp(From, To);
       Changed = true;
diff --git a/llvm/lib/IR/Value.cpp b/llvm/lib/IR/Value.cpp
index b6e25c46b514d8..d47c705be53bbf 100644
--- a/llvm/lib/IR/Value.cpp
+++ b/llvm/lib/IR/Value.cpp
@@ -977,9 +977,10 @@ Align Value::getPointerAlignment(const DataLayout &DL) const {
     // Strip pointer casts to avoid creating unnecessary ptrtoint expression
     // if the only "reduction" is combining a bitcast + ptrtoint.
     CstPtr = CstPtr->stripPointerCasts();
-    if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
-            const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
-            /*OnlyIfReduced=*/true))) {
+    if (auto *CstInt =
+            dyn_cast_if_present<ConstantInt>(ConstantExpr::getPtrToInt(
+                const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
+                /*OnlyIfReduced=*/true))) {
       size_t TrailingZeros = CstInt->getValue().countr_zero();
       // While the actual alignment may be large, elsewhere we have
       // an arbitrary upper alignmet limit, so let's clamp to it.
diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index 8aba28026306a5..374f06f85b030d 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -684,7 +684,7 @@ void Verifier::visitGlobalValue(const GlobalValue &GV) {
       const Metadata *Op = Associated->getOperand(0).get();
       Check(Op, "associated metadata must have a global value", GO, Associated);
 
-      const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
+      const auto *VM = dyn_cast_if_present<ValueAsMetadata>(Op);
       Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
       if (VM) {
         Check(isa<PointerType>(VM->getValue()->getType()),
@@ -1187,8 +1187,8 @@ void Verifier::visitDIDerivedType(const DIDerivedType &N) {
 
   if (N.getTag() == dwarf::DW_TAG_set_type) {
     if (auto *T = N.getRawBaseType()) {
-      auto *Enum = dyn_cast_or_null<DICompositeType>(T);
-      auto *Basic = dyn_cast_or_null<DIBasicType>(T);
+      auto *Enum = dyn_cast_if_present<DICompositeType>(T);
+      auto *Basic = dyn_cast_if_present<DIBasicType>(T);
       CheckDI(
           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
@@ -1352,7 +1352,7 @@ void Verifier::visitDICompileUnit(const DICompileUnit &N) {
   if (auto *Array = N.getRawEnumTypes()) {
     CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
     for (Metadata *Op : N.getEnumTypes()->operands()) {
-      auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
+      auto *Enum = dyn_cast_if_present<DICompositeType>(Op);
       CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
               "invalid enum type", &N, N.getEnumTypes(), Op);
     }
@@ -1427,7 +1427,7 @@ void Verifier::visitDISubprogram(const DISubprogram &N) {
     CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
     // There's no good way to cross the CU boundary to insert a nested
     // DISubprogram definition in one CU into a type defined in another CU.
-    auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
+    auto *CT = dyn_cast_if_present<DICompositeType>(N.getRawScope());
     if (CT && CT->getRawIdentifier() &&
         M.getContext().isODRUniquingDebugTypes())
       CheckDI(N.getDeclaration(),
@@ -1640,7 +1640,7 @@ void Verifier::visitModuleIdents() {
   for (const MDNode *N : Idents->operands()) {
     Check(N->getNumOperands() == 1,
           "incorrect number of operands in llvm.ident metadata", N);
-    Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
+    Check(dyn_cast_if_present<MDString>(N->getOperand(0)),
           ("invalid value for llvm.ident metadata entry operand"
            "(the operand should be a string)"),
           N->getOperand(0));
@@ -1658,7 +1658,7 @@ void Verifier::visitModuleCommandLines() {
   for (const MDNode *N : CommandLines->operands()) {
     Check(N->getNumOperands() == 1,
           "incorrect number of operands in llvm.commandline metadata", N);
-    Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
+    Check(dyn_cast_if_present<MDString>(N->getOperand(0)),
           ("invalid value for llvm.commandline metadata entry operand"
            "(the operand should be a string)"),
           N->getOperand(0));
@@ -1713,7 +1713,7 @@ Verifier::visitModuleFlag(const MDNode *Op,
           "invalid behavior operand in module flag (unexpected constant)",
           Op->getOperand(0));
   }
-  MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
+  MDString *ID = dyn_cast_if_present<MDString>(Op->getOperand(1));
   Check(ID, "invalid ID operand in module flag (expected metadata string)",
         Op->getOperand(1));
 
@@ -1812,11 +1812,11 @@ void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
     Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
           "expected a Function or null", FuncMDO);
   };
-  auto Node = dyn_cast_or_null<MDNode>(MDO);
+  auto Node = dyn_cast_if_present<MDNode>(MDO);
   Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
   CheckFunction(Node->getOperand(0));
   CheckFunction(Node->getOperand(1));
-  auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
+  auto Count = dyn_cast_if_present<ConstantAsMetadata>(Node->getOperand(2));
   Check(Count && Count->getType()->isIntegerTy(),
         "expected an integer constant", Node->getOperand(2));
 }
@@ -2863,7 +2863,7 @@ void Verifier::visitFunction(const Function &F) {
   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
     // Be careful about using DILocation here since we might be dealing with
     // broken code (this is the Verifier after all).
-    const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
+    const DILocation *DL = dyn_cast_if_present<DILocation>(Node);
     if (!DL)
       return;
     if (!Seen.insert(DL).second)
@@ -2896,7 +2896,7 @@ void Verifier::visitFunction(const Function &F) {
       // The llvm.loop annotations also contain two DILocations.
       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
-          VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
+          VisitDebugLoc(I, dyn_cast_if_present<MDNode>(MD->getOperand(i)));
       if (BrokenDebugInfo)
         return;
     }
@@ -3691,7 +3691,7 @@ void Verifier::verifyMustTailCall(CallInst &CI) {
   Instruction *Next = CI.getNextNode();
 
   // Handle the optional bitcast.
-  if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
+  if (BitCastInst *BI = dyn_cast_if_present<BitCastInst>(Next)) {
     Check(BI->getOperand(0) == RetVal,
           "bitcast following musttail call must use the call", BI);
     RetVal = BI;
@@ -3699,7 +3699,7 @@ void Verifier::verifyMustTailCall(CallInst &CI) {
   }
 
   // Check the return.
-  ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
+  ReturnInst *Ret = dyn_cast_if_present<ReturnInst>(Next);
   Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
   Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
             isa<UndefValue>(Ret->getReturnValue()),
@@ -6077,7 +6077,7 @@ void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
       const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
       assert(CV.size() > 0 && "Uncolored block");
       for (BasicBlock *ColorFirstBB : CV)
-        if (dyn_cast_or_null<FuncletPadInst>(ColorFirstBB->getFirstNonPHI()))
+        if (dyn_cast_if_present<FuncletPadInst>(ColorFirstBB->getFirstNonPHI()))
           InEHFunclet = true;
 
       // Check for funclet operand bundle
@@ -6445,8 +6445,8 @@ void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
 }
 
 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
-  DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
-  DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
+  DILocalVariable *V = dyn_cast_if_present<DILocalVariable>(I.getRawVariable());
+  DIExpression *E = dyn_cast_if_present<DIExpression>(I.getRawExpression());
 
   // We don't know whether this intrinsic verified correctly.
   if (!V || !E || !E->isValid())
@@ -6516,7 +6516,7 @@ void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
 }
 
 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
-  DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
+  DIExpression *E = dyn_cast_if_present<DIExpression>(I.getRawExpression());
 
   // We don't know whether this intrinsic verified correctly.
   if (!E || !E->isValid())
@@ -6528,7 +6528,7 @@ void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
       return;
     // We allow EntryValues for swift async arguments, as they have an
     // ABI-guarantee to be turned into a specific register.
-    if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
+    if (auto *ArgLoc = dyn_cast_if_present<Argument>(VarValue);
         ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
       return;
   }
@@ -6914,7 +6914,7 @@ static bool IsScalarTBAANodeImpl(const MDNode *MD,
       return false;
   }
 
-  auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
+  auto *Parent = dyn_cast_if_present<MDNode>(MD->getOperand(1));
   return Parent && Visited.insert(Parent).second &&
          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
 }
@@ -7002,8 +7002,8 @@ bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
             "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
             &I);
 
-  MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
-  MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
+  MDNode *BaseNode = dyn_cast_if_present<MDNode>(MD->getOperand(0));
+  MDNode *AccessType = dyn_cast_if_present<MDNode>(MD->getOperand(1));
 
   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
 
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index 05836fd28f5288..94715f475b134e 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -281,7 +281,7 @@ void llvm::computeLTOCacheKey(
       AddUsedThings(S);
       // If this is an alias, we also care about any types/etc. that the aliasee
       // may reference.
-      if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
+      if (auto *AS = dyn_cast_if_present<AliasSummary>(S))
         AddUsedThings(AS->getBaseObject());
     }
 
diff --git a/llvm/lib/Linker/LinkModules.cpp b/llvm/lib/Linker/LinkModules.cpp
index 4fe1f1a0f51833..8902e46ed40a5c 100644
--- a/llvm/lib/Linker/LinkModules.cpp
+++ b/llvm/lib/Linker/LinkModules.cpp
@@ -131,7 +131,7 @@ getMinVisibility(GlobalValue::VisibilityTypes A,
 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
                                    const GlobalVariable *&GVar) {
   const GlobalValue *GVal = M.getNamedValue(ComdatName);
-  if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
+  if (const auto *GA = dyn_cast_if_present<GlobalAlias>(GVal)) {
     GVal = GA->getAliaseeObject();
     if (!GVal)
       // We cannot resolve the size of the aliasee yet.
@@ -139,7 +139,7 @@ bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
                        "': COMDAT key involves incomputable alias size.");
   }
 
-  GVar = dyn_cast_or_null<GlobalVariable>(GVal);
+  GVar = dyn_cast_if_present<GlobalVariable>(GVal);
   if (!GVar)
     return emitError(
         "Linking COMDATs named '" + ComdatName +
diff --git a/llvm/lib/MC/MCObjectStreamer.cpp b/llvm/lib/MC/MCObjectStreamer.cpp
index d11ccfb5e269f7..63bc16a9396ae7 100644
--- a/llvm/lib/MC/MCObjectStreamer.cpp
+++ b/llvm/lib/MC/MCObjectStreamer.cpp
@@ -227,7 +227,7 @@ static bool canReuseDataFragment(const MCDataFragment &F,
 
 MCDataFragment *
 MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) {
-  MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
+  MCDataFragment *F = dyn_cast_if_present<MCDataFragment>(getCurrentFragment());
   if (!F || !canReuseDataFragment(*F, *Assembler, STI)) {
     F = new MCDataFragment();
     insert(F);
@@ -295,7 +295,7 @@ void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
   // If there is a current fragment, mark the symbol as pointing into it.
   // Otherwise queue the label and set its fragment pointer when we emit the
   // next fragment.
-  auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
+  auto *F = dyn_cast_if_present<MCDataFragment>(getCurrentFragment());
   if (F && !(getAssembler().isBundlingEnabled() &&
              getAssembler().getRelaxAll())) {
     Symbol->setFragment(F);
@@ -329,7 +329,7 @@ void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc,
 
   MCStreamer::emitLabel(Symbol, Loc);
   getAssembler().registerSymbol(*Symbol);
-  auto *DF = dyn_cast_or_null<MCDataFragment>(F);
+  auto *DF = dyn_cast_if_present<MCDataFragment>(F);
   Symbol->setOffset(Offset);
   if (DF) {
     Symbol->setFragment(F);
diff --git a/llvm/lib/MC/MCParser/ELFAsmParser.cpp b/llvm/lib/MC/MCParser/ELFAsmParser.cpp
index 93e1d2f44b8c56..3178a1bdc77412 100644
--- a/llvm/lib/MC/MCParser/ELFAsmParser.cpp
+++ b/llvm/lib/MC/MCParser/ELFAsmParser.cpp
@@ -486,7 +486,8 @@ bool ELFAsmParser::parseLinkedToSym(MCSymbolELF *&LinkedToSym) {
     }
     return TokError("invalid linked-to symbol");
   }
-  LinkedToSym = dyn_cast_or_null<MCSymbolELF>(getContext().lookupSymbol(Name));
+  LinkedToSym =
+      dyn_cast_if_present<MCSymbolELF>(getContext().lookupSymbol(Name));
   if (!LinkedToSym || !LinkedToSym->isInSection())
     return Error(StartLoc, "linked-to symbol is not in a section: " + Name);
   return false;
diff --git a/llvm/lib/MC/MCParser/MasmParser.cpp b/llvm/lib/MC/MCParser/MasmParser.cpp
index 51563ea86a6c52..162c41c67796fd 100644
--- a/llvm/lib/MC/MCParser/MasmParser.cpp
+++ b/llvm/lib/MC/MCParser/MasmParser.cpp
@@ -3478,7 +3478,7 @@ bool MasmParser::parseDirectiveEquate(StringRef IDVal, StringRef Name,
   MCSymbol *Sym = getContext().getOrCreateSymbol(Var.Name);
 
   const MCConstantExpr *PrevValue =
-      Sym->isVariable() ? dyn_cast_or_null<MCConstantExpr>(
+      Sym->isVariable() ? dyn_cast_if_present<MCConstantExpr>(
                               Sym->getVariableValue(/*SetUsed=*/false))
                         : nullptr;
   if (Var.IsText || !PrevValue || PrevValue->getValue() != Value) {
diff --git a/llvm/lib/MC/MachObjectWriter.cpp b/llvm/lib/MC/MachObjectWriter.cpp
index d17e6e125d8727..b2e817eeb7e9ae 100644
--- a/llvm/lib/MC/MachObjectWriter.cpp
+++ b/llvm/lib/MC/MachObjectWriter.cpp
@@ -767,7 +767,7 @@ uint64_t MachObjectWriter::writeObject(MCAssembler &Asm,
   if (!Asm.CGProfile.empty()) {
     MCSection *CGProfileSection = Asm.getContext().getMachOSection(
         "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
-    MCDataFragment *Frag = dyn_cast_or_null<MCDataFragment>(
+    MCDataFragment *Frag = dyn_cast_if_present<MCDataFragment>(
         &*CGProfileSection->getFragmentList().begin());
     assert(Frag && "call graph profile section not reserved");
     Frag->getContents().clear();
diff --git a/llvm/lib/Object/ArchiveWriter.cpp b/llvm/lib/Object/ArchiveWriter.cpp
index 2f70c9edd13ed8..7f36c5472b6d00 100644
--- a/llvm/lib/Object/ArchiveWriter.cpp
+++ b/llvm/lib/Object/ArchiveWriter.cpp
@@ -548,7 +548,7 @@ uint16_t getAuxMaxAlignment(uint16_t AuxHeaderSize, AuxiliaryHeader *AuxHeader,
 // members. This ensures that when these members are loaded they are aligned in
 // memory.
 static uint32_t getMemberAlignment(SymbolicFile *SymObj) {
-  XCOFFObjectFile *XCOFFObj = dyn_cast_or_null<XCOFFObjectFile>(SymObj);
+  XCOFFObjectFile *XCOFFObj = dyn_cast_if_present<XCOFFObjectFile>(SymObj);
   if (!XCOFFObj)
     return MinBigArchiveMemDataAlign;
 
diff --git a/llvm/lib/ObjectYAML/ELFEmitter.cpp b/llvm/lib/ObjectYAML/ELFEmitter.cpp
index 94b0529f761052..bc3927184378ed 100644
--- a/llvm/lib/ObjectYAML/ELFEmitter.cpp
+++ b/llvm/lib/ObjectYAML/ELFEmitter.cpp
@@ -981,7 +981,7 @@ void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
     Symbols = *Doc.DynamicSymbols;
 
   ELFYAML::RawContentSection *RawSec =
-      dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
+      dyn_cast_if_present<ELFYAML::RawContentSection>(YAMLSec);
   if (RawSec && (RawSec->Content || RawSec->Size)) {
     bool HasSymbolsDescription =
         (IsStatic && Doc.Symbols) || (!IsStatic && Doc.DynamicSymbols);
@@ -1042,7 +1042,7 @@ void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
   SHeader.sh_addralign = YAMLSec ? (uint64_t)YAMLSec->AddressAlign : 1;
 
   ELFYAML::RawContentSection *RawSec =
-      dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
+      dyn_cast_if_present<ELFYAML::RawContentSection>(YAMLSec);
 
   SHeader.sh_offset = alignToOffset(CBA, SHeader.sh_addralign,
                                     YAMLSec ? YAMLSec->Offset : std::nullopt);
@@ -1102,7 +1102,7 @@ void ELFState<ELFT>::initDWARFSectionHeader(Elf_Shdr &SHeader, StringRef Name,
                                     YAMLSec ? YAMLSec->Offset : std::nullopt);
 
   ELFYAML::RawContentSection *RawSec =
-      dyn_cast_or_null<ELFYAML::RawContentSection>(YAMLSec);
+      dyn_cast_if_present<ELFYAML::RawContentSection>(YAMLSec);
   if (Doc.DWARF && shouldEmitDWARF(*Doc.DWARF, Name)) {
     if (RawSec && (RawSec->Content || RawSec->Size))
       reportError("cannot specify section '" + Name +
diff --git a/llvm/lib/ProfileData/InstrProf.cpp b/llvm/lib/ProfileData/InstrProf.cpp
index 649d814cfd9de0..10de91664d34dd 100644
--- a/llvm/lib/ProfileData/InstrProf.cpp
+++ b/llvm/lib/ProfileData/InstrProf.cpp
@@ -1312,7 +1312,8 @@ bool isIRPGOFlagSet(const Module *M) {
   if (!IRInstrVar->hasInitializer())
     return false;
 
-  auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
+  auto *InitVal =
+      dyn_cast_if_present<ConstantInt>(IRInstrVar->getInitializer());
   if (!InitVal)
     return false;
   return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
diff --git a/llvm/lib/Support/YAMLTraits.cpp b/llvm/lib/Support/YAMLTraits.cpp
index 4aaf59be2ce502..351bc84e1fdc6b 100644
--- a/llvm/lib/Support/YAMLTraits.cpp
+++ b/llvm/lib/Support/YAMLTraits.cpp
@@ -127,7 +127,7 @@ void Input::beginMapping() {
   if (EC)
     return;
   // CurrentNode can be null if the document is empty.
-  MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
+  MapHNode *MN = dyn_cast_if_present<MapHNode>(CurrentNode);
   if (MN) {
     MN->ValidKeys.clear();
   }
@@ -191,7 +191,7 @@ void Input::endMapping() {
   if (EC)
     return;
   // CurrentNode can be null if the document is empty.
-  MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
+  MapHNode *MN = dyn_cast_if_present<MapHNode>(CurrentNode);
   if (!MN)
     return;
   for (const auto &NN : MN->Mapping) {
@@ -431,7 +431,7 @@ Input::HNode *Input::createHNodes(Node *N) {
     auto mapHNode = new (MapHNodeAllocator.Allocate()) MapHNode(N);
     for (KeyValueNode &KVN : *Map) {
       Node *KeyNode = KVN.getKey();
-      ScalarNode *Key = dyn_cast_or_null<ScalarNode>(KeyNode);
+      ScalarNode *Key = dyn_cast_if_present<ScalarNode>(KeyNode);
       Node *Value = KVN.getValue();
       if (!Key || !Value) {
         if (!Key)
diff --git a/llvm/lib/TableGen/Error.cpp b/llvm/lib/TableGen/Error.cpp
index dabb265ef80ca1..57506ddbc80629 100644
--- a/llvm/lib/TableGen/Error.cpp
+++ b/llvm/lib/TableGen/Error.cpp
@@ -157,8 +157,9 @@ void PrintFatalError(const RecordVal *RecVal, const Twine &Msg) {
 // Check an assertion: Obtain the condition value and be sure it is true.
 // If not, print a nonfatal error along with the message.
 void CheckAssert(SMLoc Loc, Init *Condition, Init *Message) {
-  auto *CondValue = dyn_cast_or_null<IntInit>(Condition->convertInitializerTo(
-      IntRecTy::get(Condition->getRecordKeeper())));
+  auto *CondValue =
+      dyn_cast_if_present<IntInit>(Condition->convertInitializerTo(
+          IntRecTy::get(Condition->getRecordKeeper())));
   if (!CondValue)
     PrintError(Loc, "assert condition must of type bit, bits, or int.");
   else if (!CondValue->getValue()) {
diff --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp
index aa981fdab4b3e6..c3e37192dfa495 100644
--- a/llvm/lib/TableGen/Record.cpp
+++ b/llvm/lib/TableGen/Record.cpp
@@ -832,7 +832,7 @@ Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
         return StringInit::get(RK, LHSd->getAsString());
 
-      if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
+      if (IntInit *LHSi = dyn_cast_if_present<IntInit>(
               LHS->convertInitializerTo(IntRecTy::get(RK))))
         return StringInit::get(RK, LHSi->getAsString());
 
@@ -882,7 +882,7 @@ Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
     break;
 
   case NOT:
-    if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
+    if (IntInit *LHSi = dyn_cast_if_present<IntInit>(
             LHS->convertInitializerTo(IntRecTy::get(RK))))
       return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
     break;
@@ -937,7 +937,7 @@ Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
     break;
 
   case LOG2:
-    if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
+    if (IntInit *LHSi = dyn_cast_if_present<IntInit>(
             LHS->convertInitializerTo(IntRecTy::get(RK)))) {
       int64_t LHSv = LHSi->getValue();
       if (LHSv <= 0) {
@@ -1051,7 +1051,7 @@ static StringInit *interleaveIntList(const ListInit *List,
   RecordKeeper &RK = List->getRecordKeeper();
   if (List->size() == 0)
     return StringInit::get(RK, "");
-  IntInit *Element = dyn_cast_or_null<IntInit>(
+  IntInit *Element = dyn_cast_if_present<IntInit>(
       List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
   if (!Element)
     return nullptr;
@@ -1059,7 +1059,7 @@ static StringInit *interleaveIntList(const ListInit *List,
 
   for (unsigned I = 1, E = List->size(); I < E; ++I) {
     Result.append(Delim->getValue());
-    IntInit *Element = dyn_cast_or_null<IntInit>(
+    IntInit *Element = dyn_cast_if_present<IntInit>(
         List->getElement(I)->convertInitializerTo(IntRecTy::get(RK)));
     if (!Element)
       return nullptr;
@@ -1098,9 +1098,9 @@ Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
 std::optional<bool> BinOpInit::CompareInit(unsigned Opc, Init *LHS,
                                            Init *RHS) const {
   // First see if we have two bit, bits, or int.
-  IntInit *LHSi = dyn_cast_or_null<IntInit>(
+  IntInit *LHSi = dyn_cast_if_present<IntInit>(
       LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
-  IntInit *RHSi = dyn_cast_or_null<IntInit>(
+  IntInit *RHSi = dyn_cast_if_present<IntInit>(
       RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
 
   if (LHSi && RHSi) {
@@ -1433,9 +1433,9 @@ Init *BinOpInit::Fold(Record *CurRec) const {
   case SHL:
   case SRA:
   case SRL: {
-    IntInit *LHSi = dyn_cast_or_null<IntInit>(
+    IntInit *LHSi = dyn_cast_if_present<IntInit>(
         LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
-    IntInit *RHSi = dyn_cast_or_null<IntInit>(
+    IntInit *RHSi = dyn_cast_if_present<IntInit>(
         RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
     if (LHSi && RHSi) {
       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
@@ -1619,7 +1619,7 @@ static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
       if (!Include)
         return nullptr;
       if (IntInit *IncludeInt =
-              dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
+              dyn_cast_if_present<IntInit>(Include->convertInitializerTo(
                   IntRecTy::get(LHS->getRecordKeeper())))) {
         if (IncludeInt->getValue())
           NewList.push_back(Item);
@@ -1693,7 +1693,7 @@ Init *TernOpInit::Fold(Record *CurRec) const {
   }
 
   case IF: {
-    if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
+    if (IntInit *LHSi = dyn_cast_if_present<IntInit>(
             LHS->convertInitializerTo(IntRecTy::get(RK)))) {
       if (LHSi->getValue())
         return MHS;
@@ -1839,7 +1839,7 @@ Init *TernOpInit::resolveReferences(Resolver &R) const {
   Init *lhs = LHS->resolveReferences(R);
 
   if (getOpcode() == IF && lhs != LHS) {
-    if (IntInit *Value = dyn_cast_or_null<IntInit>(
+    if (IntInit *Value = dyn_cast_if_present<IntInit>(
             lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
       // Short-circuit
       if (Value->getValue())
@@ -2486,7 +2486,7 @@ Init *CondOpInit::Fold(Record *CurRec) const {
     Init *Cond = getCond(i);
     Init *Val = getVal(i);
 
-    if (IntInit *CondI = dyn_cast_or_null<IntInit>(
+    if (IntInit *CondI = dyn_cast_if_present<IntInit>(
             Cond->convertInitializerTo(IntRecTy::get(RK)))) {
       if (CondI->getValue())
         return Val->convertInitializerTo(getValType());
diff --git a/llvm/lib/TableGen/TGParser.cpp b/llvm/lib/TableGen/TGParser.cpp
index e7dcb91ba20a60..75dbc9a458b30e 100644
--- a/llvm/lib/TableGen/TGParser.cpp
+++ b/llvm/lib/TableGen/TGParser.cpp
@@ -972,7 +972,7 @@ bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
   if (!CurVal)
     CurVal = ParseValue(nullptr);
 
-  IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
+  IntInit *II = dyn_cast_if_present<IntInit>(CurVal);
   if (!II)
     return TokError("expected integer or bitrange");
 
@@ -992,7 +992,7 @@ bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
     Lex.Lex(); // eat
 
     Init *I_End = ParseValue(nullptr);
-    IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
+    IntInit *II_End = dyn_cast_if_present<IntInit>(I_End);
     if (!II_End) {
       TokError("expected integer value as end of range");
       return true;
diff --git a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
index 3882e843fb69b8..54a111cbc13dc2 100644
--- a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
@@ -5404,7 +5404,7 @@ SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
     SDValue FnOp = Op.getOperand(1);
     SDValue IncomingFPOp = Op.getOperand(2);
     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
-    auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
+    auto *Fn = dyn_cast_if_present<Function>(GSD ? GSD->getGlobal() : nullptr);
     if (!Fn)
       report_fatal_error(
           "llvm.eh.recoverfp must take a function as the first argument");
@@ -20641,8 +20641,8 @@ static SDValue trySimplifySrlAddToRshrnb(SDValue Srl, SelectionDAG &DAG,
   else
     return SDValue();
 
-  auto SrlOp1 =
-      dyn_cast_or_null<ConstantSDNode>(DAG.getSplatValue(Srl->getOperand(1)));
+  auto SrlOp1 = dyn_cast_if_present<ConstantSDNode>(
+      DAG.getSplatValue(Srl->getOperand(1)));
   if (!SrlOp1)
     return SDValue();
   unsigned ShiftValue = SrlOp1->getZExtValue();
@@ -20652,8 +20652,8 @@ static SDValue trySimplifySrlAddToRshrnb(SDValue Srl, SelectionDAG &DAG,
   SDValue Add = Srl->getOperand(0);
   if (Add->getOpcode() != ISD::ADD || !Add->hasOneUse())
     return SDValue();
-  auto AddOp1 =
-      dyn_cast_or_null<ConstantSDNode>(DAG.getSplatValue(Add->getOperand(1)));
+  auto AddOp1 = dyn_cast_if_present<ConstantSDNode>(
+      DAG.getSplatValue(Add->getOperand(1)));
   if (!AddOp1)
     return SDValue();
   uint64_t AddValue = AddOp1->getZExtValue();
@@ -21479,7 +21479,7 @@ static bool findMoreOptimalIndexType(const MaskedGatherScatterSDNode *N,
            Index.getOperand(0).getOpcode() == ISD::STEP_VECTOR) {
     SDValue RHS = Index.getOperand(1);
     if (auto *Shift =
-            dyn_cast_or_null<ConstantSDNode>(DAG.getSplatValue(RHS))) {
+            dyn_cast_if_present<ConstantSDNode>(DAG.getSplatValue(RHS))) {
       int64_t Step = (int64_t)Index.getOperand(0).getConstantOperandVal(1);
       Stride = Step << Shift->getZExtValue();
     }
diff --git a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
index 9da59ef2a8062b..301d82c8d98532 100644
--- a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
@@ -126,7 +126,7 @@ AArch64FunctionInfo::AArch64FunctionInfo(const Function &F,
     StringRef ProbeKind;
     if (F.hasFnAttribute("probe-stack"))
       ProbeKind = F.getFnAttribute("probe-stack").getValueAsString();
-    else if (const auto *PS = dyn_cast_or_null<MDString>(
+    else if (const auto *PS = dyn_cast_if_present<MDString>(
                  F.getParent()->getModuleFlag("probe-stack")))
       ProbeKind = PS->getString();
     if (ProbeKind.size()) {
diff --git a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
index b5b8b68291786d..2c17d33a7adedf 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
@@ -976,7 +976,7 @@ static std::optional<Instruction *> instCombineSVECmpNE(InstCombiner &IC,
 
   // Check that we have a compare of zero..
   auto *SplatValue =
-      dyn_cast_or_null<ConstantInt>(getSplatValue(II.getArgOperand(2)));
+      dyn_cast_if_present<ConstantInt>(getSplatValue(II.getArgOperand(2)));
   if (!SplatValue || !SplatValue->isZero())
     return std::nullopt;
 
@@ -1594,7 +1594,7 @@ static std::optional<Instruction *> instCombineSVETBL(InstCombiner &IC,
 
   // Check whether OpIndices is a constant splat value < minimal element count
   // of result.
-  auto *SplatValue = dyn_cast_or_null<ConstantInt>(getSplatValue(OpIndices));
+  auto *SplatValue = dyn_cast_if_present<ConstantInt>(getSplatValue(OpIndices));
   if (!SplatValue ||
       SplatValue->getValue().uge(VTy->getElementCount().getKnownMinValue()))
     return std::nullopt;
@@ -1692,7 +1692,7 @@ static std::optional<Instruction *> instCombineSVESDIV(InstCombiner &IC,
   Value *DivVec = II.getOperand(2);
 
   Value *SplatValue = getSplatValue(DivVec);
-  ConstantInt *SplatConstantInt = dyn_cast_or_null<ConstantInt>(SplatValue);
+  ConstantInt *SplatConstantInt = dyn_cast_if_present<ConstantInt>(SplatValue);
   if (!SplatConstantInt)
     return std::nullopt;
   APInt Divisor = SplatConstantInt->getValue();
@@ -2167,15 +2167,16 @@ bool AArch64TTIImpl::isExtPartOfAvgExpr(const Instruction *ExtUser, Type *Dst,
   // Look for trunc/shl/add before trying to match the pattern.
   const Instruction *Add = ExtUser;
   auto *AddUser =
-      dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
+      dyn_cast_if_present<Instruction>(Add->getUniqueUndroppableUser());
   if (AddUser && AddUser->getOpcode() == Instruction::Add)
     Add = AddUser;
 
-  auto *Shr = dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
+  auto *Shr = dyn_cast_if_present<Instruction>(Add->getUniqueUndroppableUser());
   if (!Shr || Shr->getOpcode() != Instruction::LShr)
     return false;
 
-  auto *Trunc = dyn_cast_or_null<Instruction>(Shr->getUniqueUndroppableUser());
+  auto *Trunc =
+      dyn_cast_if_present<Instruction>(Shr->getUniqueUndroppableUser());
   if (!Trunc || Trunc->getOpcode() != Instruction::Trunc ||
       Src->getScalarSizeInBits() !=
           cast<CastInst>(Trunc)->getDestTy()->getScalarSizeInBits())
diff --git a/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp b/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
index 238269cf27bd78..85031f01dc7189 100644
--- a/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
+++ b/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
@@ -4897,7 +4897,7 @@ bool AArch64AsmParser::parseImmExpr(int64_t &Out) {
   SMLoc L = getLoc();
   if (check(getParser().parseExpression(Expr), L, "expected expression"))
     return true;
-  const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
+  const MCConstantExpr *Value = dyn_cast_if_present<MCConstantExpr>(Expr);
   if (check(!Value, L, "expected constant expression"))
     return true;
   Out = Value->getValue();
@@ -6984,7 +6984,7 @@ bool AArch64AsmParser::parseDirectiveInst(SMLoc Loc) {
     const MCExpr *Expr = nullptr;
     if (check(getParser().parseExpression(Expr), L, "expected expression"))
       return true;
-    const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
+    const MCConstantExpr *Value = dyn_cast_if_present<MCConstantExpr>(Expr);
     if (check(!Value, L, "expected constant expression"))
       return true;
     getTargetStreamer().emitInst(Value->getValue());
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp b/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp
index 87b1957c799e2c..119115368760d7 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp
@@ -2140,7 +2140,7 @@ bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
   // of reverse. If it worked like a normal combiner, the rsq would form before
   // we saw a sqrt call.
   auto *FDiv =
-      dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
+      dyn_cast_if_present<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
   if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
       FDiv->getFPAccuracy() >= 1.0f &&
       canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
diff --git a/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp b/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp
index 0c21382e5c225e..ad79a3d69c6c1a 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp
@@ -1449,8 +1449,8 @@ bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
   // If they are not float/double, each function has to its
   // operand separately.
   double opr0 = 0.0, opr1 = 0.0;
-  ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0);
-  ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1);
+  ConstantFP *fpopr0 = dyn_cast_if_present<ConstantFP>(copr0);
+  ConstantFP *fpopr1 = dyn_cast_if_present<ConstantFP>(copr1);
   if (fpopr0) {
     opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64)
              ? fpopr0->getValueAPF().convertToDouble()
@@ -1580,7 +1580,7 @@ bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
     return true;
 
   case AMDGPULibFunc::EI_POWN: {
-    if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
+    if (ConstantInt *iopr1 = dyn_cast_if_present<ConstantInt>(copr1)) {
       double val = (double)iopr1->getSExtValue();
       Res0 = pow(opr0, val);
       return true;
@@ -1589,7 +1589,7 @@ bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
   }
 
   case AMDGPULibFunc::EI_ROOTN: {
-    if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
+    if (ConstantInt *iopr1 = dyn_cast_if_present<ConstantInt>(copr1)) {
       double val = (double)iopr1->getSExtValue();
       Res0 = pow(opr0, 1.0 / val);
       return true;
@@ -1637,8 +1637,8 @@ bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) {
       return false;
     }
   } else {
-    ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0);
-    ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1);
+    ConstantDataVector *CDV0 = dyn_cast_if_present<ConstantDataVector>(copr0);
+    ConstantDataVector *CDV1 = dyn_cast_if_present<ConstantDataVector>(copr1);
     for (int i = 0; i < FuncVecSize; ++i) {
       Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr;
       Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr;
diff --git a/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp b/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp
index 3437b6dc8ae0ca..80baadce529879 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp
@@ -1006,8 +1006,8 @@ bool AMDGPULibFunc::isCompatibleSignature(const FunctionType *FuncTy) const {
 
 Function *AMDGPULibFunc::getFunction(Module *M, const AMDGPULibFunc &fInfo) {
   std::string FuncName = fInfo.mangle();
-  Function *F = dyn_cast_or_null<Function>(
-    M->getValueSymbolTable().lookup(FuncName));
+  Function *F =
+      dyn_cast_if_present<Function>(M->getValueSymbolTable().lookup(FuncName));
   if (!F || F->isDeclaration())
     return nullptr;
 
@@ -1023,8 +1023,8 @@ Function *AMDGPULibFunc::getFunction(Module *M, const AMDGPULibFunc &fInfo) {
 FunctionCallee AMDGPULibFunc::getOrInsertFunction(Module *M,
                                                   const AMDGPULibFunc &fInfo) {
   std::string const FuncName = fInfo.mangle();
-  Function *F = dyn_cast_or_null<Function>(
-    M->getValueSymbolTable().lookup(FuncName));
+  Function *F =
+      dyn_cast_if_present<Function>(M->getValueSymbolTable().lookup(FuncName));
 
   if (F) {
     if (F->hasFnAttribute(Attribute::NoBuiltin))
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp b/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp
index a9f1e9bd099635..b5cf63ce29173d 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp
@@ -258,7 +258,7 @@ AMDGPUPerfHintAnalysis::FuncInfo *AMDGPUPerfHint::visit(const Function &F) {
       } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
         TargetLoweringBase::AddrMode AM;
         auto *Ptr = GetPointerBaseWithConstantOffset(GEP, AM.BaseOffs, *DL);
-        AM.BaseGV = dyn_cast_or_null<GlobalValue>(const_cast<Value *>(Ptr));
+        AM.BaseGV = dyn_cast_if_present<GlobalValue>(const_cast<Value *>(Ptr));
         AM.HasBaseReg = !AM.BaseGV;
         if (TLI->isLegalAddressingMode(*DL, AM, GEP->getResultElementType(),
                                        GEP->getPointerAddressSpace()))
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp b/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
index f1da1a61bf4dd5..bd3b14ec656359 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
@@ -760,7 +760,7 @@ InstructionCost GCNTTIImpl::getCFInstrCost(unsigned Opcode,
   switch (Opcode) {
   case Instruction::Br: {
     // Branch instruction takes about 4 slots on gfx900.
-    auto BI = dyn_cast_or_null<BranchInst>(I);
+    auto BI = dyn_cast_if_present<BranchInst>(I);
     if (BI && BI->isUnconditional())
       return SCost ? 1 : 4;
     // Suppose conditional branch takes additional 3 exec manipulations
@@ -768,7 +768,7 @@ InstructionCost GCNTTIImpl::getCFInstrCost(unsigned Opcode,
     return CBrCost;
   }
   case Instruction::Switch: {
-    auto SI = dyn_cast_or_null<SwitchInst>(I);
+    auto SI = dyn_cast_if_present<SwitchInst>(I);
     // Each case (including default) takes 1 cmp + 1 cbr instructions in
     // average.
     return (SI ? (SI->getNumCases() + 1) : 4) * (CBrCost + 1);
diff --git a/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp b/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp
index 195dc4f9a0f419..1d20ee9dd2518a 100644
--- a/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp
+++ b/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp
@@ -89,7 +89,7 @@ GetFunctionFromMDNode(MDNode *Node) {
   // Validation checks.
   size_t ExpectNumArgNodeOps = F->arg_size() + 1;
   for (size_t i = 0; i < NumKernelArgMDNodes; ++i) {
-    MDNode *ArgNode = dyn_cast_or_null<MDNode>(Node->getOperand(i + 1));
+    MDNode *ArgNode = dyn_cast_if_present<MDNode>(Node->getOperand(i + 1));
     if (ArgNode->getNumOperands() != ExpectNumArgNodeOps)
       return nullptr;
     if (!ArgNode->getOperand(0))
diff --git a/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp b/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
index c1df7ef43cadd3..7c4af4e21ec42b 100644
--- a/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
+++ b/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
@@ -181,11 +181,11 @@ ARMConstantPoolConstant::Create(const Constant *C, unsigned ID,
 }
 
 const GlobalValue *ARMConstantPoolConstant::getGV() const {
-  return dyn_cast_or_null<GlobalValue>(CVal);
+  return dyn_cast_if_present<GlobalValue>(CVal);
 }
 
 const BlockAddress *ARMConstantPoolConstant::getBlockAddress() const {
-  return dyn_cast_or_null<BlockAddress>(CVal);
+  return dyn_cast_if_present<BlockAddress>(CVal);
 }
 
 int ARMConstantPoolConstant::getExistingMachineCPValue(MachineConstantPool *CP,
diff --git a/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp b/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp
index cbc5e521086515..2486fcac0f1402 100644
--- a/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp
+++ b/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp
@@ -1017,7 +1017,7 @@ InstructionCost ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
       (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
       cast<FixedVectorType>(ValTy)->getNumElements() > 1) {
     FixedVectorType *VecValTy = cast<FixedVectorType>(ValTy);
-    FixedVectorType *VecCondTy = dyn_cast_or_null<FixedVectorType>(CondTy);
+    FixedVectorType *VecCondTy = dyn_cast_if_present<FixedVectorType>(CondTy);
     if (!VecCondTy)
       VecCondTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(VecValTy));
 
diff --git a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
index 18dccb26b87769..13394e3de810f3 100644
--- a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
+++ b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
@@ -6176,7 +6176,7 @@ bool ARMAsmParser::parseImmExpr(int64_t &Out) {
   SMLoc L = getParser().getTok().getLoc();
   if (check(getParser().parseExpression(Expr), L, "expected expression"))
     return true;
-  const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
+  const MCConstantExpr *Value = dyn_cast_if_present<MCConstantExpr>(Expr);
   if (check(!Value, L, "expected constant expression"))
     return true;
   Out = Value->getValue();
@@ -11939,7 +11939,7 @@ bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
     const MCExpr *Expr;
     if (getParser().parseExpression(Expr))
       return true;
-    const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
+    const MCConstantExpr *Value = dyn_cast_if_present<MCConstantExpr>(Expr);
     if (!Value) {
       return Error(Loc, "expected constant expression");
     }
diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp
index 9c9af6068079d3..f1ccd5b0356fd1 100644
--- a/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp
+++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp
@@ -563,7 +563,8 @@ class ARMELFStreamer : public MCELFStreamer {
   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
   /// necessary.
   void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) override {
-    if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value)) {
+    if (const MCSymbolRefExpr *SRE =
+            dyn_cast_if_present<MCSymbolRefExpr>(Value)) {
       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4)) {
         getContext().reportError(Loc, "relocated expression must be 32-bit");
         return;
@@ -645,7 +646,7 @@ class ARMELFStreamer : public MCELFStreamer {
       // This is a tentative symbol, it won't really be emitted until it's
       // actually needed.
       ElfMappingSymbolInfo *EMS = LastEMSInfo.get();
-      auto *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
+      auto *DF = dyn_cast_if_present<MCDataFragment>(getCurrentFragment());
       if (!DF)
         return;
       EMS->Loc = SMLoc();
diff --git a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
index f2d1206d02316a..dd984e90222739 100644
--- a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
+++ b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
@@ -307,7 +307,7 @@ static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
   DINodeArray Elements = CTy->getElements();
   uint32_t DimSize = 1;
   for (uint32_t I = StartDim; I < Elements.size(); ++I) {
-    if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
+    if (auto *Element = dyn_cast_if_present<DINode>(Elements[I]))
       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
         const DISubrange *SR = cast<DISubrange>(Element);
         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp b/llvm/lib/Target/BPF/BTFDebug.cpp
index ebd8447eba850e..f629ac86c27013 100644
--- a/llvm/lib/Target/BPF/BTFDebug.cpp
+++ b/llvm/lib/Target/BPF/BTFDebug.cpp
@@ -702,7 +702,7 @@ void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
   // Visit array dimensions.
   DINodeArray Elements = CTy->getElements();
   for (int I = Elements.size() - 1; I >= 0; --I) {
-    if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
+    if (auto *Element = dyn_cast_if_present<DINode>(Elements[I]))
       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
         const DISubrange *SR = cast<DISubrange>(Element);
         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
diff --git a/llvm/lib/Target/DirectX/DirectXIRPasses/PointerTypeAnalysis.cpp b/llvm/lib/Target/DirectX/DirectXIRPasses/PointerTypeAnalysis.cpp
index 97b7a41cac6da3..82ed831c8e830f 100644
--- a/llvm/lib/Target/DirectX/DirectXIRPasses/PointerTypeAnalysis.cpp
+++ b/llvm/lib/Target/DirectX/DirectXIRPasses/PointerTypeAnalysis.cpp
@@ -88,7 +88,7 @@ Type *classifyFunctionType(const Function &F, PointerTypeMap &Map) {
   if (RetTy->isPointerTy()) {
     RetTy = nullptr;
     for (const auto &B : F) {
-      const auto *RetInst = dyn_cast_or_null<ReturnInst>(B.getTerminator());
+      const auto *RetInst = dyn_cast_if_present<ReturnInst>(B.getTerminator());
       if (!RetInst)
         continue;
 
diff --git a/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp b/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
index a7d452e7227d79..5b2fdfe53c3b52 100644
--- a/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
@@ -3825,7 +3825,7 @@ bool HexagonTargetLowering::shouldReduceLoadWidth(SDNode *Load,
     return false;
   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(BO.first)) {
     auto &HTM = static_cast<const HexagonTargetMachine&>(getTargetMachine());
-    const auto *GO = dyn_cast_or_null<const GlobalObject>(GA->getGlobal());
+    const auto *GO = dyn_cast_if_present<const GlobalObject>(GA->getGlobal());
     return !GO || !HTM.getObjFileLowering()->isGlobalInSmallSection(GO, HTM);
   }
   return true;
diff --git a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
index 51ef72b873a516..b5db11d4dbbdbf 100644
--- a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
@@ -1865,7 +1865,7 @@ bool PolynomialMultiplyRecognize::recognize() {
         continue;
       Simplifier::Context C(SI);
       Value *T = PostSimp.simplify(C);
-      SelectInst *SelI = dyn_cast_or_null<SelectInst>(T);
+      SelectInst *SelI = dyn_cast_if_present<SelectInst>(T);
       if (SelI != SI) {
         Value *NewSel = C.materialize(LoopB, SI->getIterator());
         SI->replaceAllUsesWith(NewSel);
diff --git a/llvm/lib/Target/LoongArch/LoongArchTargetMachine.cpp b/llvm/lib/Target/LoongArch/LoongArchTargetMachine.cpp
index a5a4d78aceeef0..766684dbdd1a86 100644
--- a/llvm/lib/Target/LoongArch/LoongArchTargetMachine.cpp
+++ b/llvm/lib/Target/LoongArch/LoongArchTargetMachine.cpp
@@ -109,7 +109,7 @@ LoongArchTargetMachine::getSubtargetImpl(const Function &F) const {
     // function that reside in TargetOptions.
     resetTargetOptions(F);
     auto ABIName = Options.MCOptions.getABIName();
-    if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
+    if (const MDString *ModuleTargetABI = dyn_cast_if_present<MDString>(
             F.getParent()->getModuleFlag("target-abi"))) {
       auto TargetABI = LoongArchABI::getTargetABI(ABIName);
       if (TargetABI != LoongArchABI::ABI_Unknown &&
diff --git a/llvm/lib/Target/Mips/MipsISelLowering.cpp b/llvm/lib/Target/Mips/MipsISelLowering.cpp
index a0cab80243868e..37e895bc4a1ae2 100644
--- a/llvm/lib/Target/Mips/MipsISelLowering.cpp
+++ b/llvm/lib/Target/Mips/MipsISelLowering.cpp
@@ -3132,7 +3132,7 @@ void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
       const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
       StringRef Sym;
       if (const GlobalAddressSDNode *G =
-              dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
+              dyn_cast_if_present<const GlobalAddressSDNode>(TargetAddr)) {
         // We must not emit the R_MIPS_JALR relocation against data symbols
         // since this will cause run-time crashes if the linker replaces the
         // call instruction with a relative branch to the data symbol.
@@ -3142,9 +3142,9 @@ void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
           return;
         }
         Sym = G->getGlobal()->getName();
-      }
-      else if (const ExternalSymbolSDNode *ES =
-                   dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
+      } else if (const ExternalSymbolSDNode *ES =
+                     dyn_cast_if_present<const ExternalSymbolSDNode>(
+                         TargetAddr)) {
         Sym = ES->getSymbol();
       }
 
@@ -3188,7 +3188,7 @@ MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
 
   const ExternalSymbolSDNode *ES =
-      dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
+      dyn_cast_if_present<const ExternalSymbolSDNode>(Callee.getNode());
 
   // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
   // is during the lowering of a call with a byval argument which produces
@@ -3513,7 +3513,7 @@ SDValue MipsTargetLowering::LowerCallResult(
                      *DAG.getContext());
 
   const ExternalSymbolSDNode *ES =
-      dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
+      dyn_cast_if_present<const ExternalSymbolSDNode>(CLI.Callee.getNode());
   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
                            ES ? ES->getSymbol() : nullptr);
 
diff --git a/llvm/lib/Target/NVPTX/NVPTXLowerUnreachable.cpp b/llvm/lib/Target/NVPTX/NVPTXLowerUnreachable.cpp
index 34f06b548db260..7a255de9cf7249 100644
--- a/llvm/lib/Target/NVPTX/NVPTXLowerUnreachable.cpp
+++ b/llvm/lib/Target/NVPTX/NVPTXLowerUnreachable.cpp
@@ -119,7 +119,7 @@ bool NVPTXLowerUnreachable::isLoweredToTrap(const UnreachableInst &I) const {
     return false;
   if (!NoTrapAfterNoreturn)
     return true;
-  const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
+  const CallInst *Call = dyn_cast_if_present<CallInst>(I.getPrevNode());
   return Call && Call->doesNotReturn();
 }
 
diff --git a/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp b/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
index 780b22b4fbe65e..ad6803d397c264 100644
--- a/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ b/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -1550,7 +1550,7 @@ void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
 void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
   // Emit float ABI into GNU attribute
   Metadata *MD = M.getModuleFlag("float-abi");
-  MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
+  MDString *FloatABI = dyn_cast_if_present<MDString>(MD);
   if (!FloatABI)
     return;
   StringRef flt = FloatABI->getString();
diff --git a/llvm/lib/Target/PowerPC/PPCFastISel.cpp b/llvm/lib/Target/PowerPC/PPCFastISel.cpp
index 42f5a4e624c494..5f128c6f98b1fe 100644
--- a/llvm/lib/Target/PowerPC/PPCFastISel.cpp
+++ b/llvm/lib/Target/PowerPC/PPCFastISel.cpp
@@ -2076,7 +2076,7 @@ unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
 
   // If the global has the toc-data attribute then fallback to DAG-ISEL.
   if (TM.getTargetTriple().isOSAIX())
-    if (const GlobalVariable *Var = dyn_cast_or_null<GlobalVariable>(GV))
+    if (const GlobalVariable *Var = dyn_cast_if_present<GlobalVariable>(GV))
       if (Var->hasAttribute("toc-data"))
         return false;
 
diff --git a/llvm/lib/Target/PowerPC/PPCGenScalarMASSEntries.cpp b/llvm/lib/Target/PowerPC/PPCGenScalarMASSEntries.cpp
index 00931b1f63b29a..95ab9e760bd6b0 100644
--- a/llvm/lib/Target/PowerPC/PPCGenScalarMASSEntries.cpp
+++ b/llvm/lib/Target/PowerPC/PPCGenScalarMASSEntries.cpp
@@ -128,7 +128,7 @@ bool PPCGenScalarMASSEntries::runOnModule(Module &M) {
       TheUsers.push_back(User);
 
     for (auto *User : TheUsers)
-      if (auto *CI = dyn_cast_or_null<CallInst>(User)) {
+      if (auto *CI = dyn_cast_if_present<CallInst>(User)) {
         if (isCandidateSafeToLower(*CI))
           Changed |= createScalarMASSCall(Iter->second, *CI, Func);
       }
diff --git a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
index b57d185bb638b8..ca7cc2e9ca6357 100644
--- a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
@@ -515,7 +515,8 @@ static bool hasTocDataAttr(SDValue Val, unsigned PointerSize) {
   if (!GA)
     return false;
 
-  const GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(GA->getGlobal());
+  const GlobalVariable *GV =
+      dyn_cast_if_present<GlobalVariable>(GA->getGlobal());
   if (!GV)
     return false;
 
@@ -741,7 +742,7 @@ static bool isThreadPointerAcquisitionNode(SDValue Base, SelectionDAG *CurDAG) {
 
   // The ADD_TLS note is explicitly acquiring the thread pointer (X13/R13).
   RegisterSDNode *AddFirstOpReg =
-      dyn_cast_or_null<RegisterSDNode>(ADDTLSOp1.getNode());
+      dyn_cast_if_present<RegisterSDNode>(ADDTLSOp1.getNode());
   if (AddFirstOpReg &&
       AddFirstOpReg->getReg() == Subtarget.getThreadPointerRegister())
       return true;
diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index acaf98b62fd94d..691d5c0220782a 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -5438,7 +5438,7 @@ static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
       // ExternalSymbol's, then we pick up the user-declared version.
       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
       if (const Function *F =
-              dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
+              dyn_cast_if_present<Function>(Mod->getNamedValue(SymName)))
         return getAIXFuncEntryPointSymbolSDNode(F);
 
       // On AIX, direct function calls reference the symbol for the function's
diff --git a/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp b/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp
index 4c9f5ff18bb647..e95d587faeb190 100644
--- a/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp
+++ b/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp
@@ -108,7 +108,8 @@ bool PPCLowerMASSVEntries::handlePowSpecialCases(CallInst *CI, Function &Func,
     return false;
 
   if (Constant *Exp = dyn_cast<Constant>(CI->getArgOperand(1)))
-    if (ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(Exp->getSplatValue())) {
+    if (ConstantFP *CFP =
+            dyn_cast_if_present<ConstantFP>(Exp->getSplatValue())) {
       // If the argument is 0.75 or 0.25 it is cheaper to turn it into pow
       // intrinsic so that it could be optimzed as sequence of sqrt's.
       if (!CI->hasNoInfs() || !CI->hasApproxFunc())
diff --git a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp
index d67351102bc1cd..5369c35fe1512c 100644
--- a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp
+++ b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp
@@ -57,14 +57,15 @@ const MCFixup *RISCVMCExpr::getPCRelHiFixup(const MCFragment **DFOut) const {
     return nullptr;
 
   const MCSymbol *AUIPCSymbol = &AUIPCSRE->getSymbol();
-  const auto *DF = dyn_cast_or_null<MCDataFragment>(AUIPCSymbol->getFragment());
+  const auto *DF =
+      dyn_cast_if_present<MCDataFragment>(AUIPCSymbol->getFragment());
 
   if (!DF)
     return nullptr;
 
   uint64_t Offset = AUIPCSymbol->getOffset();
   if (DF->getContents().size() == Offset) {
-    DF = dyn_cast_or_null<MCDataFragment>(DF->getNextNode());
+    DF = dyn_cast_if_present<MCDataFragment>(DF->getNextNode());
     if (!DF)
       return nullptr;
     Offset = 0;
diff --git a/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp b/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
index 0fd514fa87cd2f..be0f8f7a38e0e5 100644
--- a/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
+++ b/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
@@ -382,7 +382,7 @@ void RISCVAsmPrinter::emitStartOfAsmFile(Module &M) {
   RISCVTargetStreamer &RTS =
       static_cast<RISCVTargetStreamer &>(*OutStreamer->getTargetStreamer());
   if (const MDString *ModuleTargetABI =
-          dyn_cast_or_null<MDString>(M.getModuleFlag("target-abi")))
+          dyn_cast_if_present<MDString>(M.getModuleFlag("target-abi")))
     RTS.setTargetABI(RISCVABI::getTargetABI(ModuleTargetABI->getString()));
   if (TM.getTargetTriple().isOSBinFormatELF())
     emitAttributes();
diff --git a/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp b/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp
index 5ad1e082344e77..a4b60d55c5b073 100644
--- a/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp
@@ -94,14 +94,14 @@ static std::pair<Value *, Value *> matchStridedConstant(Constant *StartC) {
   unsigned NumElts = cast<FixedVectorType>(StartC->getType())->getNumElements();
 
   // Check that the start value is a strided constant.
-  auto *StartVal =
-      dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement((unsigned)0));
+  auto *StartVal = dyn_cast_if_present<ConstantInt>(
+      StartC->getAggregateElement((unsigned)0));
   if (!StartVal)
     return std::make_pair(nullptr, nullptr);
   APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
   ConstantInt *Prev = StartVal;
   for (unsigned i = 1; i != NumElts; ++i) {
-    auto *C = dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement(i));
+    auto *C = dyn_cast_if_present<ConstantInt>(StartC->getAggregateElement(i));
     if (!C)
       return std::make_pair(nullptr, nullptr);
 
@@ -552,7 +552,7 @@ bool RISCVGatherScatterLowering::runOnFunction(Function &F) {
 
   // Remove any dead phis.
   while (!MaybeDeadPHIs.empty()) {
-    if (auto *Phi = dyn_cast_or_null<PHINode>(MaybeDeadPHIs.pop_back_val()))
+    if (auto *Phi = dyn_cast_if_present<PHINode>(MaybeDeadPHIs.pop_back_val()))
       RecursivelyDeleteDeadPHINode(Phi);
   }
 
diff --git a/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp b/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
index 3abdb6003659fa..7bca6db2b085ff 100644
--- a/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
+++ b/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
@@ -222,7 +222,7 @@ RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
     // function that reside in TargetOptions.
     resetTargetOptions(F);
     auto ABIName = Options.MCOptions.getABIName();
-    if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
+    if (const MDString *ModuleTargetABI = dyn_cast_if_present<MDString>(
             F.getParent()->getModuleFlag("target-abi"))) {
       auto TargetABI = RISCVABI::getTargetABI(ABIName);
       if (TargetABI != RISCVABI::ABI_Unknown &&
diff --git a/llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp b/llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp
index 629db8e2eb4d04..624ddcfa00a12d 100644
--- a/llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp
@@ -414,7 +414,7 @@ bool SPIRVCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
   // be sure to emit its type and function declaration here. It will be hoisted
   // globally later.
   if (Info.Callee.isGlobal()) {
-    CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
+    CF = dyn_cast_if_present<const Function>(Info.Callee.getGlobal());
     // TODO: support constexpr casts and indirect calls.
     if (CF == nullptr)
       return false;
diff --git a/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp b/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp
index 1f97e0f761c04d..cc5336f2cd1fd3 100644
--- a/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp
+++ b/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp
@@ -456,7 +456,7 @@ InstructionCost SystemZTTIImpl::getArithmeticInstrCost(
     if (const Constant *C = dyn_cast<Constant>(Args[1])) {
       const ConstantInt *CVal =
           (C->getType()->isVectorTy()
-               ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
+               ? dyn_cast_if_present<const ConstantInt>(C->getSplatValue())
                : dyn_cast<const ConstantInt>(C));
       if (CVal && (CVal->getValue().isPowerOf2() ||
                    CVal->getValue().isNegatedPowerOf2()))
diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp b/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
index 99dc9797f6df92..9b465c8ceff561 100644
--- a/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
+++ b/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
@@ -423,7 +423,7 @@ isRightAfterData(MCFragment *CurrentFragment,
   //       it, returns true.
   //     - Otherwise returns false.
   //   - If the fragment is not a DataFragment, returns false.
-  if (auto *DF = dyn_cast_or_null<MCDataFragment>(F))
+  if (auto *DF = dyn_cast_if_present<MCDataFragment>(F))
     return DF != PrevInstPosition.first ||
            DF->getContents().size() != PrevInstPosition.second;
 
@@ -561,7 +561,7 @@ void X86AsmBackend::emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst)
   PrevInst = Inst;
   MCFragment *CF = OS.getCurrentFragment();
   PrevInstPosition = std::make_pair(CF, getSizeForInstFragment(CF));
-  if (auto *F = dyn_cast_or_null<MCRelaxableFragment>(CF))
+  if (auto *F = dyn_cast_if_present<MCRelaxableFragment>(CF))
     F->setAllowAutoPadding(CanPadInst);
 
   if (!canPadBranches(OS))
diff --git a/llvm/lib/Target/X86/X86FrameLowering.cpp b/llvm/lib/Target/X86/X86FrameLowering.cpp
index c0d358ead2787b..9ed3af64f659a5 100644
--- a/llvm/lib/Target/X86/X86FrameLowering.cpp
+++ b/llvm/lib/Target/X86/X86FrameLowering.cpp
@@ -3414,7 +3414,8 @@ static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD,
     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
     if (!NodeName || !NodeVal)
       continue;
-    ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
+    ConstantInt *ValConst =
+        dyn_cast_if_present<ConstantInt>(NodeVal->getValue());
     if (ValConst && NodeName->getString() == LiteralName) {
       return ValConst->getZExtValue();
     }
diff --git a/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp b/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
index 7ec59c74f5f58c..c9e81bbde3072a 100644
--- a/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
+++ b/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
@@ -96,7 +96,7 @@ namespace {
     bool isRIPRelative() const {
       if (BaseType != RegBase) return false;
       if (RegisterSDNode *RegNode =
-            dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
+              dyn_cast_if_present<RegisterSDNode>(Base_Reg.getNode()))
         return RegNode->getReg() == X86::RIP;
       return false;
     }
@@ -388,8 +388,8 @@ namespace {
           // Don't count if the other operand is SP.
           RegisterSDNode *RegNode;
           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
-              (RegNode = dyn_cast_or_null<RegisterSDNode>(
-                 OtherOp->getOperand(1).getNode())))
+              (RegNode = dyn_cast_if_present<RegisterSDNode>(
+                   OtherOp->getOperand(1).getNode())))
             if ((RegNode->getReg() == X86::ESP) ||
                 (RegNode->getReg() == X86::RSP))
               continue;
diff --git a/llvm/lib/Target/X86/X86ISelLowering.cpp b/llvm/lib/Target/X86/X86ISelLowering.cpp
index 99c492087a4585..98e0f845e4baff 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -26134,7 +26134,7 @@ SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
     SDValue FnOp = Op.getOperand(1);
     SDValue IncomingFPOp = Op.getOperand(2);
     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
-    auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
+    auto *Fn = dyn_cast_if_present<Function>(GSD ? GSD->getGlobal() : nullptr);
     if (!Fn)
       report_fatal_error(
           "llvm.eh.recoverfp must take a function as the first argument");
diff --git a/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp b/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp
index e46fc034cc2696..bbef3831afd736 100644
--- a/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp
+++ b/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp
@@ -379,7 +379,7 @@ static Value *simplifyX86varShift(const IntrinsicInst &II,
       continue;
     }
 
-    auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
+    auto *COp = dyn_cast_if_present<ConstantInt>(CElt);
     if (!COp)
       return nullptr;
 
@@ -1696,9 +1696,9 @@ static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
 
   // See if we're dealing with constant values.
   auto *C0 = dyn_cast<Constant>(Op0);
-  auto *CI0 =
-      C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
-         : nullptr;
+  auto *CI0 = C0 ? dyn_cast_if_present<ConstantInt>(
+                       C0->getAggregateElement((unsigned)0))
+                 : nullptr;
 
   // Attempt to constant fold.
   if (CILength && CIIndex) {
@@ -1830,12 +1830,12 @@ static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
   // See if we're dealing with constant values.
   auto *C0 = dyn_cast<Constant>(Op0);
   auto *C1 = dyn_cast<Constant>(Op1);
-  auto *CI00 =
-      C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
-         : nullptr;
-  auto *CI10 =
-      C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
-         : nullptr;
+  auto *CI00 = C0 ? dyn_cast_if_present<ConstantInt>(
+                        C0->getAggregateElement((unsigned)0))
+                  : nullptr;
+  auto *CI10 = C1 ? dyn_cast_if_present<ConstantInt>(
+                        C1->getAggregateElement((unsigned)0))
+                  : nullptr;
 
   // Constant Fold - insert bottom Length bits starting at the Index'th bit.
   if (CI00 && CI10) {
@@ -2538,12 +2538,12 @@ X86TTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
 
     // See if we're dealing with constant values.
     auto *C1 = dyn_cast<Constant>(Op1);
-    auto *CILength =
-        C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
-           : nullptr;
-    auto *CIIndex =
-        C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
-           : nullptr;
+    auto *CILength = C1 ? dyn_cast_if_present<ConstantInt>(
+                              C1->getAggregateElement((unsigned)0))
+                        : nullptr;
+    auto *CIIndex = C1 ? dyn_cast_if_present<ConstantInt>(
+                             C1->getAggregateElement((unsigned)1))
+                       : nullptr;
 
     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
     if (Value *V = simplifyX86extrq(II, Op0, CILength, CIIndex, IC.Builder)) {
@@ -2603,9 +2603,9 @@ X86TTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
 
     // See if we're dealing with constant values.
     auto *C1 = dyn_cast<Constant>(Op1);
-    auto *CI11 =
-        C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
-           : nullptr;
+    auto *CI11 = C1 ? dyn_cast_if_present<ConstantInt>(
+                          C1->getAggregateElement((unsigned)1))
+                    : nullptr;
 
     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
     if (CI11) {
diff --git a/llvm/lib/Target/X86/X86Subtarget.cpp b/llvm/lib/Target/X86/X86Subtarget.cpp
index d63f1ca1695b20..fed661c8d2771d 100644
--- a/llvm/lib/Target/X86/X86Subtarget.cpp
+++ b/llvm/lib/Target/X86/X86Subtarget.cpp
@@ -206,7 +206,7 @@ X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV,
     return X86II::MO_COFFSTUB;
   }
 
-  const Function *F = dyn_cast_or_null<Function>(GV);
+  const Function *F = dyn_cast_if_present<Function>(GV);
 
   if (isTargetELF()) {
     if (is64Bit() && F && (CallingConv::X86_RegCall == F->getCallingConv()))
diff --git a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
index 8a04987e768a12..e69a9e425997ff 100644
--- a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
+++ b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
@@ -4758,7 +4758,7 @@ InstructionCost X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
                                             const Instruction *I) {
   // TODO: Handle other cost kinds.
   if (CostKind != TTI::TCK_RecipThroughput) {
-    if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
+    if (auto *SI = dyn_cast_if_present<StoreInst>(I)) {
       // Store instruction with index and scale costs 2 Uops.
       // Check the preceding GEP to identify non-const indices.
       if (auto *GEP = dyn_cast<GetElementPtrInst>(SI->getPointerOperand())) {
diff --git a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
index f37b4dc938d304..6a9435d0181cf1 100644
--- a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
@@ -2208,7 +2208,7 @@ static void rewritePHIs(BasicBlock &BB) {
   // Special case for CleanupPad: all EH blocks must have the same unwind edge
   // so we need to create an additional "dispatcher" block.
   if (auto *CleanupPad =
-          dyn_cast_or_null<CleanupPadInst>(BB.getFirstNonPHI())) {
+          dyn_cast_if_present<CleanupPadInst>(BB.getFirstNonPHI())) {
     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
     for (BasicBlock *Pred : Preds) {
       if (CatchSwitchInst *CS =
@@ -2225,7 +2225,7 @@ static void rewritePHIs(BasicBlock &BB) {
 
   LandingPadInst *LandingPad = nullptr;
   PHINode *ReplPHI = nullptr;
-  if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) {
+  if ((LandingPad = dyn_cast_if_present<LandingPadInst>(BB.getFirstNonPHI()))) {
     // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
     // We replace the original landing pad with a PHINode that will collect the
     // results from all of them.
@@ -2856,7 +2856,7 @@ salvageDebugInfoImpl(SmallDenseMap<Argument *, AllocaInst *, 4> &ArgToAllocaMap,
     ++InsertPt;
   Builder.SetInsertPoint(&F->getEntryBlock(), InsertPt);
 
-  while (auto *Inst = dyn_cast_or_null<Instruction>(Storage)) {
+  while (auto *Inst = dyn_cast_if_present<Instruction>(Storage)) {
     if (auto *LdInst = dyn_cast<LoadInst>(Inst)) {
       Storage = LdInst->getPointerOperand();
       // FIXME: This is a heuristic that works around the fact that
diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 7758b52abc2046..361d17b6f90df8 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -1387,7 +1387,7 @@ static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) {
       // Both operands of the CmpInst are Constant. So that we could evaluate
       // it immediately to get the destination.
       auto *ConstResult =
-          dyn_cast_or_null<ConstantInt>(ConstantFoldCompareInstOperands(
+          dyn_cast_if_present<ConstantInt>(ConstantFoldCompareInstOperands(
               CondCmp->getPredicate(), Cond0, Cond1, DL));
       if (!ConstResult)
         return false;
diff --git a/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp b/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp
index 40cc00d2c78c28..4aca6d3cf07645 100644
--- a/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp
+++ b/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp
@@ -31,7 +31,7 @@ static bool convertAnnotation2Metadata(Module &M) {
     return false;
 
   auto *Annotations = M.getGlobalVariable("llvm.global.annotations");
-  auto *C = dyn_cast_or_null<Constant>(Annotations);
+  auto *C = dyn_cast_if_present<Constant>(Annotations);
   if (!C || C->getNumOperands() != 1)
     return false;
 
diff --git a/llvm/lib/Transforms/IPO/Attributor.cpp b/llvm/lib/Transforms/IPO/Attributor.cpp
index d8e290cbc8a4d0..86a5fc21b6f904 100644
--- a/llvm/lib/Transforms/IPO/Attributor.cpp
+++ b/llvm/lib/Transforms/IPO/Attributor.cpp
@@ -1416,7 +1416,7 @@ Attributor::getAssumedConstant(const IRPosition &IRP,
                                  UsedAssumedInformation)) {
     if (Values.empty())
       return std::nullopt;
-    if (auto *C = dyn_cast_or_null<Constant>(
+    if (auto *C = dyn_cast_if_present<Constant>(
             AAPotentialValues::getSingleValue(*this, AA, IRP, Values)))
       return C;
   }
@@ -2443,7 +2443,7 @@ ChangeStatus Attributor::cleanupIR() {
 
     // Do not replace uses in returns if the value is a must-tail call we will
     // not delete.
-    if (auto *RI = dyn_cast_or_null<ReturnInst>(I)) {
+    if (auto *RI = dyn_cast_if_present<ReturnInst>(I)) {
       if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
         if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
           return;
@@ -2507,7 +2507,7 @@ ChangeStatus Attributor::cleanupIR() {
   }
 
   for (const auto &V : InvokeWithDeadSuccessor)
-    if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
+    if (InvokeInst *II = dyn_cast_if_present<InvokeInst>(V)) {
       assert(isRunOn(*II->getFunction()) &&
              "Cannot replace an invoke outside the current SCC!");
       bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
@@ -2540,7 +2540,7 @@ ChangeStatus Attributor::cleanupIR() {
     ConstantFoldTerminator(I->getParent());
   }
   for (const auto &V : ToBeChangedToUnreachableInsts)
-    if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
+    if (Instruction *I = dyn_cast_if_present<Instruction>(V)) {
       LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
                         << "\n");
       assert(isRunOn(*I->getFunction()) &&
@@ -2550,7 +2550,7 @@ ChangeStatus Attributor::cleanupIR() {
     }
 
   for (const auto &V : ToBeDeletedInsts) {
-    if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
+    if (Instruction *I = dyn_cast_if_present<Instruction>(V)) {
       if (auto *CB = dyn_cast<CallBase>(I)) {
         assert((isa<IntrinsicInst>(CB) || isRunOn(*I->getFunction())) &&
                "Cannot delete an instruction outside the current SCC!");
diff --git a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
index 8e1f782f7cd811..fce3e4d349dbbc 100644
--- a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -1994,7 +1994,7 @@ struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
     // We handle memory intrinsics explicitly, at least the first (=
     // destination) and second (=source) arguments as we know how they are
     // accessed.
-    if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) {
+    if (auto *MI = dyn_cast_if_present<MemIntrinsic>(getCtxI())) {
       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
       int64_t LengthVal = AA::RangeTy::Unknown;
       if (Length)
@@ -4257,10 +4257,10 @@ struct AAIsDeadFloating : public AAIsDeadValueImpl {
   /// See AbstractAttribute::updateImpl(...).
   ChangeStatus updateImpl(Attributor &A) override {
     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
-    if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
+    if (auto *SI = dyn_cast_if_present<StoreInst>(I)) {
       if (!isDeadStore(A, *SI))
         return indicatePessimisticFixpoint();
-    } else if (auto *FI = dyn_cast_or_null<FenceInst>(I)) {
+    } else if (auto *FI = dyn_cast_if_present<FenceInst>(I)) {
       if (!isDeadFence(A, *FI))
         return indicatePessimisticFixpoint();
     } else {
@@ -6294,7 +6294,7 @@ struct AAValueSimplifyImpl : AAValueSimplify {
       // Check if we need to adjust the insertion point to make sure the IR is
       // valid.
       Instruction *IP = dyn_cast<Instruction>(U.getUser());
-      if (auto *PHI = dyn_cast_or_null<PHINode>(IP))
+      if (auto *PHI = dyn_cast_if_present<PHINode>(IP))
         IP = PHI->getIncomingBlock(U)->getTerminator();
       if (auto *NewV = manifestReplacementValue(A, IP)) {
         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue()
@@ -6818,7 +6818,7 @@ struct AAHeapToStackFunction final : public AAHeapToStack {
         A.getAssumedConstant(V, AA, UsedAssumedInformation);
     if (!SimpleV)
       return APInt(64, 0);
-    if (auto *CI = dyn_cast_or_null<ConstantInt>(*SimpleV))
+    if (auto *CI = dyn_cast_if_present<ConstantInt>(*SimpleV))
       return CI->getValue();
     return std::nullopt;
   }
@@ -10838,7 +10838,7 @@ struct AAPotentialValuesImpl : AAPotentialValues {
                         Function *AnchorScope) const {
 
     IRPosition ValIRP = IRPosition::value(V);
-    if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) {
+    if (auto *CB = dyn_cast_if_present<CallBase>(CtxI)) {
       for (const auto &U : CB->args()) {
         if (U.get() != &V)
           continue;
@@ -11129,7 +11129,7 @@ struct AAPotentialValuesFloating : AAPotentialValuesImpl {
     bool NoValueYet = !C.has_value();
     if (NoValueYet || isa_and_nonnull<UndefValue>(*C))
       return true;
-    if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) {
+    if (auto *CI = dyn_cast_if_present<ConstantInt>(*C)) {
       if (CI->isZero())
         Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
       else
diff --git a/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp b/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp
index 5cc8258a495a6e..727e210e65961b 100644
--- a/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp
+++ b/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp
@@ -49,7 +49,7 @@ ConstantInt *CrossDSOCFI::extractNumericTypeId(MDNode *MD) {
   auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(1));
   if (!TM)
     return nullptr;
-  auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
+  auto C = dyn_cast_if_present<ConstantInt>(TM->getValue());
   if (!C) return nullptr;
   // We are looking for i64 constants.
   if (C->getBitWidth() != 64) return nullptr;
diff --git a/llvm/lib/Transforms/IPO/FunctionImport.cpp b/llvm/lib/Transforms/IPO/FunctionImport.cpp
index 49b3f2b085e18f..9b66acbec93fc9 100644
--- a/llvm/lib/Transforms/IPO/FunctionImport.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionImport.cpp
@@ -965,7 +965,7 @@ static bool checkVariableImport(
   // linkonce_odr). In that case we cannot accurately do this checking.
   auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
                                                   const ValueInfo &VI) {
-    auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
+    auto *GVS = dyn_cast_if_present<GlobalVarSummary>(
         Index.findSummaryInModule(VI, ModulePath));
     return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
            !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
@@ -1477,7 +1477,7 @@ void llvm::thinLTOFinalizeInModule(Module &TheModule,
     // Remove declarations from comdats, including available_externally
     // as this is a declaration for the linker, and will be dropped eventually.
     // It is illegal for comdats to contain declarations.
-    auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
+    auto *GO = dyn_cast_if_present<GlobalObject>(&GV);
     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
       if (GO->getComdat()->getName() == GO->getName())
         NonPrevailingComdats.insert(GO->getComdat());
diff --git a/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp b/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp
index a4c12006ee2433..1083e8027ef1f9 100644
--- a/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp
@@ -468,9 +468,9 @@ Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
     return nullptr;
 
   Constant *Const = LastVisited->second;
-  return dyn_cast_or_null<Constant>(Swap ?
-        simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
-      : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
+  return dyn_cast_if_present<Constant>(
+      Swap ? simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
+           : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
 }
 
 Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
diff --git a/llvm/lib/Transforms/IPO/GlobalSplit.cpp b/llvm/lib/Transforms/IPO/GlobalSplit.cpp
index 84e9c219f935cd..90abb845804240 100644
--- a/llvm/lib/Transforms/IPO/GlobalSplit.cpp
+++ b/llvm/lib/Transforms/IPO/GlobalSplit.cpp
@@ -43,7 +43,7 @@ static bool splitGlobal(GlobalVariable &GV) {
     return false;
 
   // We currently only know how to split ConstantStructs.
-  auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
+  auto *Init = dyn_cast_if_present<ConstantStruct>(GV.getInitializer());
   if (!Init)
     return false;
 
diff --git a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
index fabb3c5fb921df..44dcee8aa4f90a 100644
--- a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
+++ b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
@@ -151,7 +151,7 @@ bool unlikelyExecuted(BasicBlock &BB) {
   // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp).
   if (blockEndsInUnreachable(BB)) {
     if (auto *CI =
-            dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
+            dyn_cast_if_present<CallInst>(BB.getTerminator()->getPrevNode()))
       if (CI->hasFnAttr(Attribute::NoReturn))
         return false;
     return true;
diff --git a/llvm/lib/Transforms/IPO/IROutliner.cpp b/llvm/lib/Transforms/IPO/IROutliner.cpp
index a6e19df7c5f1ff..709b463a5a77d6 100644
--- a/llvm/lib/Transforms/IPO/IROutliner.cpp
+++ b/llvm/lib/Transforms/IPO/IROutliner.cpp
@@ -733,7 +733,7 @@ static void moveFunctionData(Function &Old, Function &New,
         // several locations.
         auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {
           if (DISubprogram *SP = New.getSubprogram())
-            if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
+            if (auto *Loc = dyn_cast_if_present<DILocation>(MD))
               return DILocation::get(New.getContext(), Loc->getLine(),
                                      Loc->getColumn(), SP, nullptr);
           return MD;
diff --git a/llvm/lib/Transforms/IPO/MergeFunctions.cpp b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
index c8c011d94e4a3b..62ee1c15bc40ad 100644
--- a/llvm/lib/Transforms/IPO/MergeFunctions.cpp
+++ b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
@@ -574,7 +574,7 @@ void MergeFunctions::filterInstsUnrelatedToPDI(
       if (DILocVar->isParameter()) {
         LLVM_DEBUG(dbgs() << "  Parameter: ");
         LLVM_DEBUG(DILocVar->print(dbgs()));
-        AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
+        AllocaInst *AI = dyn_cast_if_present<AllocaInst>(DDI->getAddress());
         if (AI) {
           LLVM_DEBUG(dbgs() << "  Processing alloca users: ");
           LLVM_DEBUG(dbgs() << "\n");
diff --git a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
index b2665161c090df..7a90219923af5f 100644
--- a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
+++ b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
@@ -3138,7 +3138,7 @@ ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) {
       // Asummes and "assume-like" (dbg, lifetime, ...) are handled first, the
       // former is collected the latter is ignored.
       if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
-        if (auto *AI = dyn_cast_or_null<AssumeInst>(II)) {
+        if (auto *AI = dyn_cast_if_present<AssumeInst>(II)) {
           ED.addAssumeInst(A, *AI);
           continue;
         }
diff --git a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
index e5f9fa1dda88e3..56536125cb3407 100644
--- a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
+++ b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
@@ -305,7 +305,8 @@ void splitAndWriteThinLTOBitcode(
   // reference the global's section directly.
   auto HasTypeMetadata = [](const GlobalObject *GO) {
     if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
-      if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
+      if (auto *AssocVM =
+              dyn_cast_if_present<ValueAsMetadata>(MD->getOperand(0)))
         if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
           if (AssocGO->hasMetadata(LLVMContext::MD_type))
             return true;
@@ -358,7 +359,7 @@ void splitAndWriteThinLTOBitcode(
         if (auto *F = dyn_cast<Function>(GV))
           return EligibleVirtualFns.count(F);
         if (auto *GVar =
-                dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject()))
+                dyn_cast_if_present<GlobalVariable>(GV->getAliaseeObject()))
           return HasTypeMetadata(GVar);
         return false;
       }));
@@ -387,7 +388,8 @@ void splitAndWriteThinLTOBitcode(
   // Remove all globals with type metadata, globals with comdats that live in
   // MergedM, and aliases pointing to such globals from the thin LTO module.
   filterModule(&M, [&](const GlobalValue *GV) {
-    if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject()))
+    if (auto *GVar =
+            dyn_cast_if_present<GlobalVariable>(GV->getAliaseeObject()))
       if (HasTypeMetadata(GVar))
         return false;
     if (const auto *C = GV->getComdat())
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 1539fa9a3269e1..79149b3b982392 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -2614,7 +2614,7 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     // Handle mul by one:
     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
       if (ConstantInt *Splat =
-              dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
+              dyn_cast_if_present<ConstantInt>(CV1->getSplatValue()))
         if (Splat->isOne())
           return CastInst::CreateIntegerCast(Arg0, II->getType(),
                                              /*isSigned=*/!Zext);
@@ -3392,7 +3392,8 @@ Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
   if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
     return eraseInstFromFunction(FI);
 
-  if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
+  if (auto *PFI =
+          dyn_cast_if_present<FenceInst>(FI.getPrevNonDebugInstruction()))
     if (isIdenticalOrStrongerFence(PFI, &FI))
       return eraseInstFromFunction(FI);
   return nullptr;
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index 6629ca840a67c0..a13aeb2c10a528 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1559,7 +1559,7 @@ static Type *shrinkFPConstantVector(Value *V) {
     if (isa<UndefValue>(CV->getAggregateElement(i)))
       continue;
 
-    auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
+    auto *CFP = dyn_cast_if_present<ConstantFP>(CV->getAggregateElement(i));
     if (!CFP)
       return nullptr;
 
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 289976718e52f3..17fd55bf9bba0b 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -4273,7 +4273,7 @@ foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
     return nullptr;
 
   // Can we fold (XShAmt+YShAmt) ?
-  auto *NewShAmt = dyn_cast_or_null<Constant>(
+  auto *NewShAmt = dyn_cast_if_present<Constant>(
       simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
                       /*isNUW=*/false, SQ.getWithInstruction(&I)));
   if (!NewShAmt)
@@ -6021,7 +6021,7 @@ static bool isChainSelectCmpBranch(const SelectInst *SI) {
   const BasicBlock *BB = SI->getParent();
   if (!BB)
     return false;
-  auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
+  auto *BI = dyn_cast_if_present<BranchInst>(BB->getTerminator());
   if (!BI || BI->getNumSuccessors() != 2)
     return false;
   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
index b7958978c450c9..a8e7b6dec6964c 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
@@ -106,7 +106,7 @@ Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
     return nullptr;
 
   // Can we fold (ShAmt0+ShAmt1) ?
-  auto *NewShAmt = dyn_cast_or_null<Constant>(
+  auto *NewShAmt = dyn_cast_if_present<Constant>(
       simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
                       SQ.getWithInstruction(Sh0)));
   if (!NewShAmt)
@@ -236,7 +236,7 @@ dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
       return nullptr;
 
     // Can we simplify (MaskShAmt+ShiftShAmt) ?
-    auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
+    auto *SumOfShAmts = dyn_cast_if_present<Constant>(simplifyAddInst(
         MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
     if (!SumOfShAmts)
       return nullptr; // Did not simplify.
@@ -272,7 +272,7 @@ dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
       return nullptr;
 
     // Can we simplify (ShiftShAmt-MaskShAmt) ?
-    auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
+    auto *ShAmtsDiff = dyn_cast_if_present<Constant>(simplifySubInst(
         ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
     if (!ShAmtsDiff)
       return nullptr; // Did not simplify.
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp b/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp
index c8b58c51d4e6ec..a297868110cd8d 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp
@@ -970,7 +970,7 @@ Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
     // FIXME: deal with multiple levels of PHI indirection?
 
     // Did we find an extraction?
-    auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
+    auto *EVI = dyn_cast_if_present<ExtractValueInst>(Elt);
     if (!EVI)
       return NotFound;
 
diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
index a7ddadc25de43c..975c08bd0a872b 100644
--- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
@@ -4348,7 +4348,7 @@ class AliasScopeTracker {
       return;
 
     auto Track = [](Metadata *ScopeList, auto &Container) {
-      const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
+      const auto *MDScopeList = dyn_cast_if_present<MDNode>(ScopeList);
       if (!MDScopeList || !Container.insert(MDScopeList).second)
         return;
       for (const auto &MDOperand : MDScopeList->operands())
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index 6468d07b4f4f45..ced2ce385cd33d 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -1306,7 +1306,7 @@ bool AddressSanitizer::ignoreAccess(Instruction *Inst, Value *Ptr) {
   // Treat memory accesses to promotable allocas as non-interesting since they
   // will not cause memory violations. This greatly speeds up the instrumented
   // executable at -O0.
-  if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))
+  if (auto AI = dyn_cast_if_present<AllocaInst>(Ptr))
     if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))
       return true;
 
diff --git a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
index ee5b819604170e..0ef51ce5bc45d7 100644
--- a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
+++ b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
@@ -113,7 +113,7 @@ static Value *getBoundsCheckCond(Value *Ptr, Value *InstVal,
 template <typename GetTrapBBT>
 static void insertBoundsCheck(Value *Or, BuilderTy &IRB, GetTrapBBT GetTrapBB) {
   // check if the comparison is always false
-  ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
+  ConstantInt *C = dyn_cast_if_present<ConstantInt>(Or);
   if (C) {
     ++ChecksSkipped;
     // If non-zero, nothing to do.
diff --git a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
index fe5a0578bd9721..2ba332f6741c32 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -348,7 +348,7 @@ class PGOCounterPromoterHelper : public LoadAndStorePromoter {
       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
       Type *Ty = LiveInValue->getType();
       IRBuilder<> Builder(InsertPos);
-      if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
+      if (auto *AddrInst = dyn_cast_if_present<IntToPtrInst>(Addr)) {
         // If isRuntimeCounterRelocationEnabled() is true then the address of
         // the store instruction is computed with two instructions in
         // InstrProfiling::getCounterAddress(). We need to copy those
@@ -1066,7 +1066,7 @@ static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
 }
 
 static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
-  auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
+  auto *MD = dyn_cast_if_present<ConstantAsMetadata>(M.getModuleFlag(Flag));
   if (!MD)
     return 0;
 
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index 539b7441d24b3c..bfd2eb478eed86 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -466,7 +466,7 @@ void MemProfiler::instrumentAddress(Instruction *OrigIns,
 // Create the variable for the profile file name.
 void createProfileFileNameVar(Module &M) {
   const MDString *MemProfFilename =
-      dyn_cast_or_null<MDString>(M.getModuleFlag("MemProfProfileFilename"));
+      dyn_cast_if_present<MDString>(M.getModuleFlag("MemProfProfileFilename"));
   if (!MemProfFilename)
     return;
   assert(!MemProfFilename->getString().empty() &&
diff --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index 94af63da38c82c..4b79250a512ef7 100644
--- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -1360,7 +1360,7 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
     if (shouldDisambiguateWarningLocation(IRB.getCurrentDebugLocation())) {
       // Try to create additional origin with debug info of the last origin
       // instruction. It may provide additional information to the user.
-      if (Instruction *OI = dyn_cast_or_null<Instruction>(Origin)) {
+      if (Instruction *OI = dyn_cast_if_present<Instruction>(Origin)) {
         assert(MS.TrackOrigins);
         auto NewDebugLoc = OI->getDebugLoc();
         // Origin update with missing or the same debug location provides no
@@ -2095,10 +2095,10 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
         return;
       Origin = getOrigin(Val);
     } else {
-      Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
+      Shadow = dyn_cast_if_present<Instruction>(getShadow(Val));
       if (!Shadow)
         return;
-      Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
+      Origin = dyn_cast_if_present<Instruction>(getOrigin(Val));
     }
     insertShadowCheck(Shadow, Origin, OrigIns);
   }
diff --git a/llvm/lib/Transforms/ObjCARC/ObjCARC.h b/llvm/lib/Transforms/ObjCARC/ObjCARC.h
index 9e68bd574851b5..1079ee7efbb759 100644
--- a/llvm/lib/Transforms/ObjCARC/ObjCARC.h
+++ b/llvm/lib/Transforms/ObjCARC/ObjCARC.h
@@ -91,7 +91,7 @@ void getEquivalentPHIs(PHINodeTy &PN, VectorTy &PHIList) {
 
 static inline MDString *getRVInstMarker(Module &M) {
   const char *MarkerKey = getRVMarkerModuleFlagStr();
-  return dyn_cast_or_null<MDString>(M.getModuleFlag(MarkerKey));
+  return dyn_cast_if_present<MDString>(M.getModuleFlag(MarkerKey));
 }
 
 /// Create a call instruction with the correct funclet token. This should be
diff --git a/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp b/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp
index c397ab63f388c4..0c6f4a7eecc4ee 100644
--- a/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp
+++ b/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp
@@ -163,7 +163,7 @@ bool ObjCARCContract::contractAutorelease(Function &F, Instruction *Autorelease,
   DependenceKind DK = Class == ARCInstKind::AutoreleaseRV
                           ? RetainAutoreleaseRVDep
                           : RetainAutoreleaseDep;
-  auto *Retain = dyn_cast_or_null<CallInst>(
+  auto *Retain = dyn_cast_if_present<CallInst>(
       findSingleDependency(DK, Arg, Autorelease->getParent(), Autorelease, PA));
 
   if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
diff --git a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
index b51e4d46bffeb2..8aa08baa8fa13a 100644
--- a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -2266,7 +2266,7 @@ bool ObjCARCOpt::OptimizeSequences(Function &F) {
 static CallInst *HasSafePathToPredecessorCall(const Value *Arg,
                                               Instruction *Retain,
                                               ProvenanceAnalysis &PA) {
-  auto *Call = dyn_cast_or_null<CallInst>(findSingleDependency(
+  auto *Call = dyn_cast_if_present<CallInst>(findSingleDependency(
       CanChangeRetainCount, Arg, Retain->getParent(), Retain, PA));
 
   // Check that the pointer is the return value of the call.
@@ -2287,7 +2287,7 @@ static CallInst *
 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
                                   Instruction *Autorelease,
                                   ProvenanceAnalysis &PA) {
-  auto *Retain = dyn_cast_or_null<CallInst>(
+  auto *Retain = dyn_cast_if_present<CallInst>(
       findSingleDependency(CanChangeRetainCount, Arg, BB, Autorelease, PA));
 
   // Check that we found a retain with the same argument.
@@ -2307,7 +2307,7 @@ FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
                                        ReturnInst *Ret,
                                        ProvenanceAnalysis &PA) {
   SmallPtrSet<Instruction *, 4> DepInsts;
-  auto *Autorelease = dyn_cast_or_null<CallInst>(
+  auto *Autorelease = dyn_cast_if_present<CallInst>(
       findSingleDependency(NeedsPositiveRetainCount, Arg, BB, Ret, PA));
 
   if (!Autorelease)
diff --git a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
index 18266ba0789897..1ed32591d604af 100644
--- a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
@@ -888,7 +888,7 @@ void State::addInfoForInductions(BasicBlock &BB) {
   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
     return;
 
-  auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
+  auto *AR = dyn_cast_if_present<SCEVAddRecExpr>(SE.getSCEV(PN));
   BasicBlock *LoopPred = L->getLoopPredecessor();
   if (!AR || AR->getLoop() != L || !LoopPred)
     return;
diff --git a/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp b/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
index d2dfc764d042bb..b893a28717ec64 100644
--- a/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
+++ b/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
@@ -108,7 +108,7 @@ static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
     else
       C = LVI->getConstant(S->getCondition(), I);
 
-    auto *CI = dyn_cast_or_null<ConstantInt>(C);
+    auto *CI = dyn_cast_if_present<ConstantInt>(C);
     if (!CI)
       continue;
 
diff --git a/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp b/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
index 008dcc53fd44fc..bb45a7a3ea59eb 100644
--- a/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
@@ -873,7 +873,7 @@ struct DSEState {
         if (I.mayThrow() && !MA)
           ThrowingBlocks.insert(I.getParent());
 
-        auto *MD = dyn_cast_or_null<MemoryDef>(MA);
+        auto *MD = dyn_cast_if_present<MemoryDef>(MA);
         if (MD && MemDefs.size() < MemorySSADefsPerBlockLimit &&
             (getLocForWrite(&I) || isMemTerminatorInst(&I)))
           MemDefs.push_back(MD);
@@ -1854,7 +1854,8 @@ struct DSEState {
         Func != LibFunc_malloc)
       return false;
     // Gracefully handle malloc with unexpected memory attributes.
-    auto *MallocDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(Malloc));
+    auto *MallocDef =
+        dyn_cast_if_present<MemoryDef>(MSSA.getMemoryAccess(Malloc));
     if (!MallocDef)
       return false;
 
diff --git a/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp b/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp
index 41c4d623617347..5cccc2e4d2a2c7 100644
--- a/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp
+++ b/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp
@@ -405,7 +405,7 @@ bool IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
 
   bool Changed = false;
   for (WeakTrackingVH &PHI : PHIs)
-    if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHI))
+    if (PHINode *PN = dyn_cast_if_present<PHINode>(&*PHI))
       Changed |= handleFloatingPointIV(L, PN);
 
   // If the loop previously had floating-point IV, ScalarEvolution
@@ -2015,9 +2015,9 @@ bool IndVarSimplify::run(Loop *L) {
   while (!DeadInsts.empty()) {
     Value *V = DeadInsts.pop_back_val();
 
-    if (PHINode *PHI = dyn_cast_or_null<PHINode>(V))
+    if (PHINode *PHI = dyn_cast_if_present<PHINode>(V))
       Changed |= RecursivelyDeleteDeadPHINode(PHI, TLI, MSSAU.get());
-    else if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
+    else if (Instruction *Inst = dyn_cast_if_present<Instruction>(V))
       Changed |=
           RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI, MSSAU.get());
   }
diff --git a/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp b/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp
index 1bf50d79e5331e..d26fb0a01bb467 100644
--- a/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp
+++ b/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp
@@ -790,7 +790,7 @@ Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
   if (Instruction *I = dyn_cast<Instruction>(V)) {
     Value *NewV = cloneInstructionWithNewAddressSpace(
         I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, PoisonUsesToFix);
-    if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
+    if (Instruction *NewI = dyn_cast_if_present<Instruction>(NewV)) {
       if (NewI->getParent() == nullptr) {
         NewI->insertBefore(I);
         NewI->takeName(I);
diff --git a/llvm/lib/Transforms/Scalar/JumpThreading.cpp b/llvm/lib/Transforms/Scalar/JumpThreading.cpp
index 8603c5cf9c022c..db0d1d5bc143f1 100644
--- a/llvm/lib/Transforms/Scalar/JumpThreading.cpp
+++ b/llvm/lib/Transforms/Scalar/JumpThreading.cpp
@@ -2195,7 +2195,7 @@ bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
     // If PredPred ends with IndirectBrInst, we can't handle it.
     if (isa<IndirectBrInst>(P->getTerminator()))
       continue;
-    if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
+    if (ConstantInt *CI = dyn_cast_if_present<ConstantInt>(
             evaluateOnPredecessorEdge(BB, P, Cond))) {
       if (CI->isZero()) {
         ZeroCount++;
diff --git a/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp b/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp
index cfe069d00bce76..fd3c93a5c79b34 100644
--- a/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp
@@ -131,7 +131,7 @@ static bool simplifyLoopInst(Loop &L, DominatorTree &DT, LoopInfo &LI,
         }
 
         if (MSSAU)
-          if (Instruction *SimpleI = dyn_cast_or_null<Instruction>(V))
+          if (Instruction *SimpleI = dyn_cast_if_present<Instruction>(V))
             if (MemoryAccess *MA = MSSA->getMemoryAccess(&I))
               if (MemoryAccess *ReplacementMA = MSSA->getMemoryAccess(SimpleI))
                 MA->replaceAllUsesWith(ReplacementMA);
diff --git a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
index 39607464dd0090..82135b41b399d0 100644
--- a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
@@ -2492,7 +2492,7 @@ LSRInstance::OptimizeLoopTermCond() {
               A = SE.getSignExtendExpr(A, B->getType());
           }
           if (const SCEVConstant *D =
-                dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
+                  dyn_cast_if_present<SCEVConstant>(getExactSDiv(B, A, SE))) {
             const ConstantInt *C = D->getValue();
             // Stride of one or negative one can have reuse with non-addresses.
             if (C->isOne() || C->isMinusOne())
@@ -2738,15 +2738,12 @@ void LSRInstance::CollectInterestingTypesAndFactors() {
         else
           OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
       }
-      if (const SCEVConstant *Factor =
-            dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
-                                                        SE, true))) {
+      if (const SCEVConstant *Factor = dyn_cast_if_present<SCEVConstant>(
+              getExactSDiv(NewStride, OldStride, SE, true))) {
         if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
           Factors.insert(Factor->getAPInt().getSExtValue());
-      } else if (const SCEVConstant *Factor =
-                   dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
-                                                               NewStride,
-                                                               SE, true))) {
+      } else if (const SCEVConstant *Factor = dyn_cast_if_present<SCEVConstant>(
+                     getExactSDiv(OldStride, NewStride, SE, true))) {
         if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
           Factors.insert(Factor->getAPInt().getSExtValue());
       }
diff --git a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
index b167120a906dfe..a7835da3a2d000 100644
--- a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
+++ b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
@@ -65,7 +65,7 @@ static bool replaceConditionalBranchesOnConstant(Instruction *II,
                                   UnsimplifiedUsers.end());
 
   for (auto &VH : Worklist) {
-    BranchInst *BI = dyn_cast_or_null<BranchInst>(VH);
+    BranchInst *BI = dyn_cast_if_present<BranchInst>(VH);
     if (!BI)
       continue;
     if (BI->isUnconditional())
diff --git a/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp b/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp
index 9d058e0d248378..287f572047aa19 100644
--- a/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp
+++ b/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp
@@ -718,7 +718,7 @@ bool MemCpyOptPass::processStoreOfLoad(StoreInst *SI, LoadInst *LI,
     // have been done on the source inside performCallSlotOptzn.
     if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
             MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA)))
-      return dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
+      return dyn_cast_if_present<CallInst>(LoadClobber->getMemoryInst());
     return nullptr;
   };
 
@@ -1322,7 +1322,7 @@ static bool hasUndefContents(MemorySSA *MSSA, BatchAAResults &AA, Value *V,
   if (MSSA->isLiveOnEntryDef(Def))
     return isa<AllocaInst>(getUnderlyingObject(V));
 
-  if (auto *II = dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
+  if (auto *II = dyn_cast_if_present<IntrinsicInst>(Def->getMemoryInst())) {
     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
       auto *LTSize = cast<ConstantInt>(II->getArgOperand(0));
 
@@ -1707,7 +1707,7 @@ bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
   // The memcpy must post-dom the memset, so limit this to the same basic
   // block. A non-local generalization is likely not worthwhile.
   if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
-    if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
+    if (auto *MDep = dyn_cast_if_present<MemSetInst>(MD->getMemoryInst()))
       if (DestClobber->getBlock() == M->getParent())
         if (processMemSetMemCpyDependence(M, MDep, BAA))
           return true;
@@ -1825,7 +1825,7 @@ bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
   MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
       CallAccess->getDefiningAccess(), Loc, BAA);
   if (auto *MD = dyn_cast<MemoryDef>(Clobber))
-    MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
+    MDep = dyn_cast_if_present<MemCpyInst>(MD->getMemoryInst());
 
   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
   // a memcpy, see if we can byval from the source of the memcpy instead of the
@@ -1922,7 +1922,7 @@ bool MemCpyOptPass::processImmutArgument(CallBase &CB, unsigned ArgNo) {
   MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
       CallAccess->getDefiningAccess(), Loc, BAA);
   if (auto *MD = dyn_cast<MemoryDef>(Clobber))
-    MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
+    MDep = dyn_cast_if_present<MemCpyInst>(MD->getMemoryInst());
 
   // If the immut argument isn't fed by a memcpy, ignore it.  If it is fed by
   // a memcpy, check that the arg equals the memcpy dest.
diff --git a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
index 7fe1a222021ebe..927c609c45df24 100644
--- a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
+++ b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
@@ -282,10 +282,10 @@ NaryReassociatePass::matchAndReassociateMinOrMax(Instruction *I,
           m_Value(LHS), m_Value(RHS));
   if (match(I, MinMaxMatcher)) {
     OrigSCEV = SE->getSCEV(I);
-    if (auto *NewMinMax = dyn_cast_or_null<Instruction>(
+    if (auto *NewMinMax = dyn_cast_if_present<Instruction>(
             tryReassociateMinOrMax(I, MinMaxMatcher, LHS, RHS)))
       return NewMinMax;
-    if (auto *NewMinMax = dyn_cast_or_null<Instruction>(
+    if (auto *NewMinMax = dyn_cast_if_present<Instruction>(
             tryReassociateMinOrMax(I, MinMaxMatcher, RHS, LHS)))
       return NewMinMax;
   }
diff --git a/llvm/lib/Transforms/Scalar/NewGVN.cpp b/llvm/lib/Transforms/Scalar/NewGVN.cpp
index 19ac9526b5f88b..d3fadc10fdbe27 100644
--- a/llvm/lib/Transforms/Scalar/NewGVN.cpp
+++ b/llvm/lib/Transforms/Scalar/NewGVN.cpp
@@ -1898,7 +1898,7 @@ NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
   // something from a previous comparison.
   for (const auto &Op : CI->operands()) {
     auto *PI = PredInfo->getPredicateInfoFor(Op);
-    if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
+    if (const auto *PBranch = dyn_cast_if_present<PredicateBranch>(PI)) {
       if (PI == LastPredInfo)
         continue;
       LastPredInfo = PI;
@@ -2148,7 +2148,7 @@ const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
   // Make sure there will be a leader to find.
   assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
   if (CC->getStoreCount() > 0) {
-    if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
+    if (auto *NL = dyn_cast_if_present<StoreInst>(CC->getNextLeader().first))
       return getMemoryAccess(NL);
     // Find the store with the minimum DFS number.
     auto *V = getMinDFSOfRange<Value>(make_filter_range(
@@ -2279,7 +2279,7 @@ void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
   // instructions before.
 
   // If it's not a memory use, set the MemoryAccess equivalence
-  auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
+  auto *InstMA = dyn_cast_if_present<MemoryDef>(getMemoryAccess(I));
   if (InstMA)
     moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
   ValueToClass[I] = NewClass;
@@ -2476,7 +2476,8 @@ void NewGVN::processOutgoingEdges(Instruction *TI, BasicBlock *B) {
       if (auto *I = dyn_cast<Instruction>(Cond)) {
         SmallPtrSet<Value *, 4> Visited;
         auto Res = performSymbolicEvaluation(I, Visited);
-        if (const auto *CE = dyn_cast_or_null<ConstantExpression>(Res.Expr)) {
+        if (const auto *CE =
+                dyn_cast_if_present<ConstantExpression>(Res.Expr)) {
           CondEvaluated = CE->getConstantValue();
           addAdditionalUsers(Res, I);
         } else {
@@ -3611,7 +3612,7 @@ void NewGVN::convertClassToDFSOrdered(
     // If there is a phi node equivalent, add it
     if (auto *PN = RealToTemp.lookup(Def)) {
       auto *PHIE =
-          dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
+          dyn_cast_if_present<PHIExpression>(ValueToExpression.lookup(Def));
       if (PHIE) {
         VDDef.Def.setInt(false);
         VDDef.Def.setPointer(PN);
@@ -3879,7 +3880,7 @@ bool NewGVN::eliminateInstructions(Function &F) {
     for (auto InstNum : BBPair.second) {
       auto *Inst = InstrFromDFSNum(InstNum);
       auto *PHI = dyn_cast<PHINode>(Inst);
-      PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
+      PHI = PHI ? PHI : dyn_cast_if_present<PHINode>(RealToTemp.lookup(Inst));
       if (!PHI)
         continue;
       auto *BB = BBPair.first;
@@ -3962,7 +3963,7 @@ bool NewGVN::eliminateInstructions(Function &F) {
           // We ignore void things because we can't get a value from them.
           if (Def && Def->getType()->isVoidTy())
             continue;
-          auto *DefInst = dyn_cast_or_null<Instruction>(Def);
+          auto *DefInst = dyn_cast_if_present<Instruction>(Def);
           if (DefInst && AllTempInstructions.count(DefInst)) {
             auto *PN = cast<PHINode>(DefInst);
 
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp b/llvm/lib/Transforms/Scalar/SROA.cpp
index 24da26c9f0f253..0cdcfc03ed22dc 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -1501,7 +1501,7 @@ findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
       UserTy = SI->getValueOperand()->getType();
     }
 
-    if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
+    if (IntegerType *UserITy = dyn_cast_if_present<IntegerType>(UserTy)) {
       // If the type is larger than the partition, skip it. We only encounter
       // this for split integer operations where we want to use the type of the
       // entity causing the split. Also skip if the type is not a byte width
@@ -5160,7 +5160,7 @@ bool SROA::deleteDeadInstructions(
     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
   bool Changed = false;
   while (!DeadInsts.empty()) {
-    Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
+    Instruction *I = dyn_cast_if_present<Instruction>(DeadInsts.pop_back_val());
     if (!I)
       continue;
     LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
diff --git a/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp b/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp
index b8c9d9d100f117..bebb00bfd4bd97 100644
--- a/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp
+++ b/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp
@@ -914,7 +914,7 @@ void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
   // If we created a GEP with constant index, and the base is loop invariant,
   // then we swap the first one with it, so LICM can move constant GEP out
   // later.
-  auto *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
+  auto *FirstGEP = dyn_cast_if_present<GetElementPtrInst>(FirstResult);
   auto *SecondGEP = dyn_cast<GetElementPtrInst>(ResultPtr);
   if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
     swapGEPOperand(FirstGEP, SecondGEP);
diff --git a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp b/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
index 7eb0ba1c2c1793..fdd5dff829d683 100644
--- a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
+++ b/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
@@ -305,7 +305,7 @@ static void buildPartialInvariantUnswitchConditionalBranch(
 
     MemorySSA *MSSA = MSSAU->getMemorySSA();
     if (auto *MemUse =
-            dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
+            dyn_cast_if_present<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
       auto *DefiningAccess = MemUse->getDefiningAccess();
       // Get the first defining access before the loop.
       while (L.contains(DefiningAccess->getBlock())) {
diff --git a/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp b/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp
index 7017f6adf3a2bb..e21fb1b8055629 100644
--- a/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp
+++ b/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp
@@ -187,7 +187,7 @@ static bool tailMergeBlocksWithSimilarFunctionTerminators(Function &F,
     // of the value computed by experimental_deoptimize.
     // I.e., we can not change `ret` to `br` for this block.
     if (auto *CI =
-            dyn_cast_or_null<CallInst>(Term->getPrevNonDebugInstruction())) {
+            dyn_cast_if_present<CallInst>(Term->getPrevNonDebugInstruction())) {
       if (Function *F = CI->getCalledFunction())
         if (Intrinsic::ID ID = F->getIntrinsicID())
           if (ID == Intrinsic::experimental_deoptimize)
diff --git a/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp b/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
index 7a5318d4404ca4..347d2fce091d7e 100644
--- a/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
+++ b/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
@@ -267,7 +267,7 @@ bool SpeculativeExecutionPass::considerHoistingFromTo(
     // Debug variable has special operand to check it's not hoisted.
     if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(U)) {
       return all_of(DVI->location_ops(), [&NotHoisted](Value *V) {
-        if (const auto *I = dyn_cast_or_null<Instruction>(V)) {
+        if (const auto *I = dyn_cast_if_present<Instruction>(V)) {
           if (!NotHoisted.contains(I))
             return true;
         }
diff --git a/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp b/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
index 7d96a3478858bd..3e3833d3e6c975 100644
--- a/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
+++ b/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
@@ -778,7 +778,7 @@ void StructurizeCFG::simplifyAffectedPhis() {
     // to achieve better register pressure.
     Q.CanUseUndef = false;
     for (WeakVH VH : AffectedPhis) {
-      if (auto Phi = dyn_cast_or_null<PHINode>(VH)) {
+      if (auto Phi = dyn_cast_if_present<PHINode>(VH)) {
         if (auto NewValue = simplifyInstruction(Phi, Q)) {
           Phi->replaceAllUsesWith(NewValue);
           Phi->eraseFromParent();
diff --git a/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp b/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp
index efa8e874b955e0..535d21cb11adf2 100644
--- a/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp
+++ b/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp
@@ -421,7 +421,7 @@ struct AssumeSimplify {
           }
           RetainedKnowledge RK =
             getKnowledgeFromBundle(cast<AssumeInst>(*Assume), BOI);
-          if (auto *Arg = dyn_cast_or_null<Argument>(RK.WasOn)) {
+          if (auto *Arg = dyn_cast_if_present<Argument>(RK.WasOn)) {
             bool HasSameKindAttr = Arg->hasAttribute(RK.AttrKind);
             if (HasSameKindAttr)
               if (!Attribute::isIntAttrKind(RK.AttrKind) ||
@@ -484,7 +484,7 @@ struct AssumeSimplify {
         if (!RK)
           continue;
         Builder.addKnowledge(RK);
-        if (auto *I = dyn_cast_or_null<Instruction>(RK.WasOn))
+        if (auto *I = dyn_cast_if_present<Instruction>(RK.WasOn))
           if (I->getParent() == InsertPt->getParent() &&
               (InsertPt->comesBefore(I) || InsertPt == I))
             InsertPt = I->getNextNode();
diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
index 8b5a6d61841209..d5a8ea83483684 100644
--- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
+++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
@@ -171,7 +171,7 @@ bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
 
   bool Changed = false;
   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
-    if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
+    if (PHINode *PN = dyn_cast_if_present<PHINode>(PHIs[i].operator Value *()))
       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
 
   return Changed;
@@ -2122,7 +2122,7 @@ BasicBlock *llvm::CreateControlFlowHub(
 
   for (auto I : DeletionCandidates) {
     if (I->use_empty())
-      if (auto Inst = dyn_cast_or_null<Instruction>(I))
+      if (auto Inst = dyn_cast_if_present<Instruction>(I))
         Inst->eraseFromParent();
   }
 
diff --git a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
index e42cdab64446e2..6dc298c552afe1 100644
--- a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
+++ b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
@@ -306,7 +306,7 @@ CallBase &llvm::versionCallSite(CallBase &CB, Value *Callee,
     // Place a clone of the optional bitcast after the new call site.
     Value *NewRetVal = NewInst;
     auto Next = OrigInst->getNextNode();
-    if (auto *BitCast = dyn_cast_or_null<BitCastInst>(Next)) {
+    if (auto *BitCast = dyn_cast_if_present<BitCastInst>(Next)) {
       assert(BitCast->getOperand(0) == OrigInst &&
              "bitcast following musttail call must use the call");
       auto NewBitCast = BitCast->clone();
@@ -317,7 +317,7 @@ CallBase &llvm::versionCallSite(CallBase &CB, Value *Callee,
     }
 
     // Place a clone of the return instruction after the new call site.
-    ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
+    ReturnInst *Ret = dyn_cast_if_present<ReturnInst>(Next);
     assert(Ret && "musttail call must precede a ret with an optional bitcast");
     auto NewRet = Ret->clone();
     if (Ret->getReturnValue())
diff --git a/llvm/lib/Transforms/Utils/CloneFunction.cpp b/llvm/lib/Transforms/Utils/CloneFunction.cpp
index c0f333364fa587..705d8fb2adc480 100644
--- a/llvm/lib/Transforms/Utils/CloneFunction.cpp
+++ b/llvm/lib/Transforms/Utils/CloneFunction.cpp
@@ -594,7 +594,7 @@ void PruningFunctionCloner::CloneBlock(
       // Or is a known constant in the caller...
       if (!Cond) {
         Value *V = VMap.lookup(BI->getCondition());
-        Cond = dyn_cast_or_null<ConstantInt>(V);
+        Cond = dyn_cast_if_present<ConstantInt>(V);
       }
 
       // Constant fold to uncond branch!
@@ -610,7 +610,7 @@ void PruningFunctionCloner::CloneBlock(
     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
     if (!Cond) { // Or known constant after constant prop in the callee...
       Value *V = VMap.lookup(SI->getCondition());
-      Cond = dyn_cast_or_null<ConstantInt>(V);
+      Cond = dyn_cast_if_present<ConstantInt>(V);
     }
     if (Cond) { // Constant fold to uncond branch!
       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
@@ -839,7 +839,7 @@ void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
   // Note that we must test the size on each iteration, the worklist can grow.
   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
     const Value *OrigV = Worklist[Idx];
-    auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
+    auto *I = dyn_cast_if_present<Instruction>(VMap.lookup(OrigV));
     if (!I)
       continue;
 
diff --git a/llvm/lib/Transforms/Utils/CodeExtractor.cpp b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
index f5abed0dd51786..8eb11e741f7149 100644
--- a/llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -1658,7 +1658,7 @@ static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
 
     // Loop info metadata may contain line locations. Fix them up.
     auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * {
-      if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
+      if (auto *Loc = dyn_cast_if_present<DILocation>(MD))
         return DebugLoc::replaceInlinedAtSubprogram(Loc, *NewSP, Ctx, Cache);
       return MD;
     };
@@ -1904,7 +1904,7 @@ bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
                                           const Function &NewFunc,
                                           AssumptionCache *AC) {
   for (auto AssumeVH : AC->assumptions()) {
-    auto *I = dyn_cast_or_null<CallInst>(AssumeVH);
+    auto *I = dyn_cast_if_present<CallInst>(AssumeVH);
     if (!I)
       continue;
 
@@ -1916,7 +1916,7 @@ bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
     // that were previously in the old function, but that have now been moved
     // to the new function.
     for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) {
-      auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH);
+      auto *AffectedCI = dyn_cast_if_present<CallInst>(AffectedValVH);
       if (!AffectedCI)
         continue;
       if (AffectedCI->getFunction() != &OldFunc)
diff --git a/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp b/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
index 87be6be018857c..acdfd08968b846 100644
--- a/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
+++ b/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
@@ -264,7 +264,7 @@ void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
       // contains summaries from the source modules if they are being imported.
       // We might have a non-null VI and get here even in that case if the name
       // matches one in this module (e.g. weak or appending linkage).
-      auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
+      auto *GVS = dyn_cast_if_present<GlobalVarSummary>(
           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
       if (GVS &&
           (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 39d5f6e53c1de4..ff7f7fdc49efb1 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -891,8 +891,8 @@ propagateMemProfMetadata(Function *Callee, CallBase &CB,
   for (const auto &Entry : VMap) {
     // See if this is a call that has been inlined and remapped, and not
     // simplified away in the process.
-    auto *OrigCall = dyn_cast_or_null<CallBase>(Entry.first);
-    auto *ClonedCall = dyn_cast_or_null<CallBase>(Entry.second);
+    auto *OrigCall = dyn_cast_if_present<CallBase>(Entry.first);
+    auto *ClonedCall = dyn_cast_if_present<CallBase>(Entry.second);
     if (!OrigCall || !ClonedCall)
       continue;
     // If the inlined callsite did not have any callsite metadata, then it isn't
@@ -1390,7 +1390,7 @@ static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) {
     // Check that the cloned RetVal exists and is a call, otherwise we cannot
     // add the attributes on the cloned RetVal. Simplification during inlining
     // could have transformed the cloned instruction.
-    auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal));
+    auto *NewRetVal = dyn_cast_if_present<CallBase>(VMap.lookup(RetVal));
     if (!NewRetVal)
       continue;
     // Backward propagation of attributes to the returned value may be incorrect
@@ -1672,7 +1672,7 @@ static void fixupLineNumbers(Function *Fn, Function::iterator FI,
     // reference inlined-at locations.
     auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode,
                               &IANodes](Metadata *MD) -> Metadata * {
-      if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
+      if (auto *Loc = dyn_cast_if_present<DILocation>(MD))
         return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes).get();
       return MD;
     };
@@ -1905,7 +1905,7 @@ void llvm::updateProfileCallee(
     uint64_t CloneEntryCount = PriorEntryCount - NewEntryCount;
     for (auto Entry : *VMap)
       if (isa<CallInst>(Entry.first))
-        if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
+        if (auto *CI = dyn_cast_if_present<CallInst>(Entry.second))
           CI->updateProfWeight(CloneEntryCount, PriorEntryCount);
   }
 
@@ -2296,7 +2296,7 @@ llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
       SmallVector<OperandBundleDef, 2> OpDefs;
 
       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
-        CallBase *ICS = dyn_cast_or_null<CallBase>(VH);
+        CallBase *ICS = dyn_cast_if_present<CallBase>(VH);
         if (!ICS)
           continue; // instruction was DCE'd or RAUW'ed to undef
 
@@ -2733,7 +2733,7 @@ llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
 
       // Delete the old return and any preceding bitcast.
       BasicBlock *CurBB = RI->getParent();
-      auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
+      auto *OldCast = dyn_cast_if_present<BitCastInst>(RI->getReturnValue());
       RI->eraseFromParent();
       if (OldCast)
         OldCast->eraseFromParent();
diff --git a/llvm/lib/Transforms/Utils/Local.cpp b/llvm/lib/Transforms/Utils/Local.cpp
index a758fb30698231..b7a04ce708e846 100644
--- a/llvm/lib/Transforms/Utils/Local.cpp
+++ b/llvm/lib/Transforms/Utils/Local.cpp
@@ -551,7 +551,7 @@ bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
     std::function<void(Value *)> AboutToDeleteCallback) {
   unsigned S = 0, E = DeadInsts.size(), Alive = 0;
   for (; S != E; ++S) {
-    auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
+    auto *I = dyn_cast_if_present<Instruction>(DeadInsts[S]);
     if (!I || !isInstructionTriviallyDead(I)) {
       DeadInsts[S] = nullptr;
       ++Alive;
@@ -1607,7 +1607,7 @@ static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
     assert(DII->getNumVariableLocationOps() == 1 &&
            "address of variable must have exactly 1 location operand.");
     if (auto *AI =
-            dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
+            dyn_cast_if_present<AllocaInst>(DII->getVariableLocationOp(0))) {
       if (std::optional<TypeSize> FragmentSize =
               AI->getAllocationSizeInBits(DL)) {
         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
@@ -1633,7 +1633,7 @@ static bool valueCoversEntireFragment(Type *ValTy, DPValue *DPV) {
     assert(DPV->getNumVariableLocationOps() == 1 &&
            "address of variable must have exactly 1 location operand.");
     if (auto *AI =
-            dyn_cast_or_null<AllocaInst>(DPV->getVariableLocationOp(0))) {
+            dyn_cast_if_present<AllocaInst>(DPV->getVariableLocationOp(0))) {
       if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
       }
@@ -1937,7 +1937,7 @@ bool llvm::LowerDbgDeclare(Function &F) {
 
   auto LowerOne = [&](auto *DDI) {
     AllocaInst *AI =
-        dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
+        dyn_cast_if_present<AllocaInst>(DDI->getVariableLocationOp(0));
     // If this is an alloca for a scalar variable, insert a dbg.value
     // at each load and store to the alloca and erase the dbg.declare.
     // The dbg.values allow tracking a variable even if it is not
@@ -2012,7 +2012,7 @@ static void insertDPValuesForPHIs(BasicBlock *BB,
   for (auto &I : *BB) {
     for (auto &DPV : I.getDbgValueRange()) {
       for (Value *V : DPV.location_ops())
-        if (auto *Loc = dyn_cast_or_null<PHINode>(V))
+        if (auto *Loc = dyn_cast_if_present<PHINode>(V))
           DbgValueMap.insert({Loc, &DPV});
     }
   }
@@ -2076,7 +2076,7 @@ void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
   for (auto &I : *BB) {
     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
       for (Value *V : DbgII->location_ops())
-        if (auto *Loc = dyn_cast_or_null<PHINode>(V))
+        if (auto *Loc = dyn_cast_if_present<PHINode>(V))
           DbgValueMap.insert({Loc, DbgII});
     }
   }
@@ -3608,7 +3608,7 @@ DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,
   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
     if (CE->getOpcode() == Instruction::IntToPtr) {
       const Value *V = CE->getOperand(0);
-      if (auto CI = dyn_cast_or_null<ConstantInt>(V))
+      if (auto CI = dyn_cast_if_present<ConstantInt>(V))
         return createIntegerExpression(*CI);
     }
   return nullptr;
diff --git a/llvm/lib/Transforms/Utils/LoopUnroll.cpp b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
index ee6f7b35750af0..5f018097e155ec 100644
--- a/llvm/lib/Transforms/Utils/LoopUnroll.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
@@ -227,7 +227,7 @@ void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
     // identified. Any remaining should be cleaned up below.
     while (!DeadInsts.empty()) {
       Value *V = DeadInsts.pop_back_val();
-      if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
+      if (Instruction *Inst = dyn_cast_if_present<Instruction>(V))
         RecursivelyDeleteTriviallyDeadInstructions(Inst);
     }
   }
diff --git a/llvm/lib/Transforms/Utils/LoopUtils.cpp b/llvm/lib/Transforms/Utils/LoopUtils.cpp
index 59485126b280ab..6568d2895ee6c7 100644
--- a/llvm/lib/Transforms/Utils/LoopUtils.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUtils.cpp
@@ -1888,7 +1888,7 @@ llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
 
     InstToDuplicate.push_back(I);
     if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
-      if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
+      if (auto *MemUse = dyn_cast_if_present<MemoryUse>(MA)) {
         // Queue the defining access to check for alias checks.
         AccessesToCheck.push_back(MemUse->getDefiningAccess());
         AccessedLocs.push_back(MemoryLocation::get(I));
diff --git a/llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp b/llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp
index 1e42d7491676db..89be62f26404f1 100644
--- a/llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp
+++ b/llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp
@@ -139,7 +139,7 @@ void StackInfoBuilder::visit(Instruction &Inst) {
   }
   if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst)) {
     for (Value *V : DVI->location_ops()) {
-      if (auto *AI = dyn_cast_or_null<AllocaInst>(V)) {
+      if (auto *AI = dyn_cast_if_present<AllocaInst>(V)) {
         if (!isInterestingAlloca(*AI))
           continue;
         AllocaInfo &AInfo = Info.AllocasToInstrument[AI];
diff --git a/llvm/lib/Transforms/Utils/PredicateInfo.cpp b/llvm/lib/Transforms/Utils/PredicateInfo.cpp
index 902977b08d1537..30435882aed0fd 100644
--- a/llvm/lib/Transforms/Utils/PredicateInfo.cpp
+++ b/llvm/lib/Transforms/Utils/PredicateInfo.cpp
@@ -97,8 +97,8 @@ struct ValueDFS {
 
 // Perform a strict weak ordering on instructions and arguments.
 static bool valueComesBefore(const Value *A, const Value *B) {
-  auto *ArgA = dyn_cast_or_null<Argument>(A);
-  auto *ArgB = dyn_cast_or_null<Argument>(B);
+  auto *ArgA = dyn_cast_if_present<Argument>(A);
+  auto *ArgB = dyn_cast_if_present<Argument>(B);
   if (ArgA && !ArgB)
     return true;
   if (ArgB && !ArgA)
@@ -221,8 +221,8 @@ struct ValueDFS_Compare {
     // See if we have real values or uses. If we have real values, we are
     // guaranteed they are instructions or arguments. No matter what, we are
     // guaranteed they are in the same block if they are instructions.
-    auto *ArgA = dyn_cast_or_null<Argument>(ADef);
-    auto *ArgB = dyn_cast_or_null<Argument>(BDef);
+    auto *ArgA = dyn_cast_if_present<Argument>(ADef);
+    auto *ArgB = dyn_cast_if_present<Argument>(BDef);
 
     if (ArgA || ArgB)
       return valueComesBefore(ArgA, ArgB);
@@ -516,7 +516,7 @@ void PredicateInfoBuilder::buildPredicateInfo() {
     }
   }
   for (auto &Assume : AC.assumptions()) {
-    if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
+    if (auto *II = dyn_cast_if_present<IntrinsicInst>(Assume))
       if (DT.isReachableFromEntry(II->getParent()))
         processAssume(II, II->getParent(), OpsToRename);
   }
diff --git a/llvm/lib/Transforms/Utils/SCCPSolver.cpp b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
index ab95698abc4399..3ed92bea22a3b7 100644
--- a/llvm/lib/Transforms/Utils/SCCPSolver.cpp
+++ b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
@@ -406,7 +406,7 @@ class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
 
 private:
   ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const {
-    return dyn_cast_or_null<ConstantInt>(getConstant(IV, Ty));
+    return dyn_cast_if_present<ConstantInt>(getConstant(IV, Ty));
   }
 
   // pushToWorkList - Helper for markConstant/markOverdefined
@@ -1085,7 +1085,7 @@ void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
     // Casts are folded by visitCastInst.
     ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
-    BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(
+    BlockAddress *Addr = dyn_cast_if_present<BlockAddress>(
         getConstant(IBRValue, IBR->getAddress()->getType()));
     if (!Addr) { // Overdefined or unknown condition?
       // All destinations are executable!
@@ -1462,7 +1462,7 @@ void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
                     ? getConstant(V2State, I.getOperand(1)->getType())
                     : I.getOperand(1);
     Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL));
-    auto *C = dyn_cast_or_null<Constant>(R);
+    auto *C = dyn_cast_if_present<Constant>(R);
     if (C) {
       // Conservatively assume that the result may be based on operands that may
       // be undef. Note that we use mergeInValue to combine the constant with
diff --git a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
index 760a626c8b6fcb..a049b98016f252 100644
--- a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
@@ -324,7 +324,7 @@ static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> A
 static Value *copyFlags(const CallInst &Old, Value *New) {
   assert(!Old.isMustTailCall() && "do not copy musttail call flags");
   assert(!Old.isNoTailCall() && "do not copy notail call flags");
-  if (auto *NewCI = dyn_cast_or_null<CallInst>(New))
+  if (auto *NewCI = dyn_cast_if_present<CallInst>(New))
     NewCI->setTailCallKind(Old.getTailCallKind());
   return New;
 }
diff --git a/llvm/lib/Transforms/Utils/SplitModule.cpp b/llvm/lib/Transforms/Utils/SplitModule.cpp
index 9c39c26d8b7af8..e3da5d6fb51cf3 100644
--- a/llvm/lib/Transforms/Utils/SplitModule.cpp
+++ b/llvm/lib/Transforms/Utils/SplitModule.cpp
@@ -91,7 +91,7 @@ static void addAllGlobalValueUsers(ClusterMapType &GVtoClusterMap,
 
 static const GlobalObject *getGVPartitioningRoot(const GlobalValue *GV) {
   const GlobalObject *GO = GV->getAliaseeObject();
-  if (const auto *GI = dyn_cast_or_null<GlobalIFunc>(GO))
+  if (const auto *GI = dyn_cast_if_present<GlobalIFunc>(GO))
     GO = GI->getResolverFunction();
   return GO;
 }
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp
index 37a356c43e29a4..93fc0d294c2a34 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp
@@ -1198,7 +1198,7 @@ bool LoopVectorizationLegality::isInvariantAddressOfReduction(Value *V) {
 
 bool LoopVectorizationLegality::isInductionPhi(const Value *V) const {
   Value *In0 = const_cast<Value *>(V);
-  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
+  PHINode *PN = dyn_cast_if_present<PHINode>(In0);
   if (!PN)
     return false;
 
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index f82e161fb846d1..3f26bc6e6ef452 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -1116,7 +1116,7 @@ void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
         RecWithFlags->dropPoisonGeneratingFlags();
       } else {
-        Instruction *Instr = dyn_cast_or_null<Instruction>(
+        Instruction *Instr = dyn_cast_if_present<Instruction>(
             CurRec->getVPSingleValue()->getUnderlyingValue());
         (void)Instr;
         assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
@@ -6758,7 +6758,7 @@ void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
   for (BasicBlock *BB : TheLoop->blocks())
     for (Instruction &I : *BB) {
       Instruction *PtrDef =
-        dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
+          dyn_cast_if_present<Instruction>(getLoadStorePointerOperand(&I));
       if (PtrDef && TheLoop->contains(PtrDef) &&
           getWideningDecision(&I, VF) != CM_GatherScatter)
         AddrDefs.insert(PtrDef);
@@ -8269,7 +8269,7 @@ VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
   VPValue *InLoopVal = nullptr;
   for (unsigned In = 0; In < NumIncoming; In++) {
     PHINode *PhiOp =
-        dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
+        dyn_cast_if_present<PHINode>(Operands[In]->getUnderlyingValue());
     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
       assert(!InLoopVal && "Found more than one in-loop reduction!");
       InLoopVal = Operands[In];
@@ -8861,7 +8861,7 @@ LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(VFRange &Range) {
         RecipeBuilder.getRecipe(IG->getInsertPos()));
     SmallVector<VPValue *, 4> StoredValues;
     for (unsigned i = 0; i < IG->getFactor(); ++i)
-      if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
+      if (auto *SI = dyn_cast_if_present<StoreInst>(IG->getMember(i))) {
         auto *StoreR =
             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
         StoredValues.push_back(StoreR->getStoredValue());
diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 9d799124074ca1..b4c4ed25bc20e9 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -4081,7 +4081,7 @@ static bool areTwoInsertFromSameBuildVector(
       if ((IE1 != VU && !IE1->hasOneUse()) || IsReusedIdx)
         IE1 = nullptr;
       else
-        IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1));
+        IE1 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE1));
     }
     if (IE2 && IE2 != VU) {
       unsigned Idx2 = getInsertIndex(IE2).value_or(*Idx1);
@@ -4090,7 +4090,7 @@ static bool areTwoInsertFromSameBuildVector(
       if ((IE2 != V && !IE2->hasOneUse()) || IsReusedIdx)
         IE2 = nullptr;
       else
-        IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2));
+        IE2 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE2));
     }
   } while (!IsReusedIdx && (IE1 || IE2));
   return false;
@@ -8951,7 +8951,7 @@ InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
 
     // If found user is an insertelement, do not calculate extract cost but try
     // to detect it as a final shuffled/identity match.
-    if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
+    if (auto *VU = dyn_cast_if_present<InsertElementInst>(EU.User)) {
       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
         if (!UsedInserts.insert(VU).second)
           continue;
@@ -11223,7 +11223,7 @@ Value *BoUpSLP::vectorizeTree(TreeEntry *E, bool PostponedPHIs) {
               InsertMask[*InsertIdx] = *InsertIdx;
             if (!Ins->hasOneUse())
               break;
-            Ins = dyn_cast_or_null<InsertElementInst>(
+            Ins = dyn_cast_if_present<InsertElementInst>(
                 Ins->getUniqueUndroppableUser());
           } while (Ins);
           SmallBitVector UseMask =
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.cpp b/llvm/lib/Transforms/Vectorize/VPlan.cpp
index 1d7df9c9575af0..f76b0ab237d6f4 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlan.cpp
@@ -90,14 +90,14 @@ VPValue::~VPValue() {
 
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
-  if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
+  if (const VPRecipeBase *R = dyn_cast_if_present<VPRecipeBase>(Def))
     R->print(OS, "", SlotTracker);
   else
     printAsOperand(OS, SlotTracker);
 }
 
 void VPValue::dump() const {
-  const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
+  const VPRecipeBase *Instr = dyn_cast_if_present<VPRecipeBase>(this->Def);
   VPSlotTracker SlotTracker(
       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
   print(dbgs(), SlotTracker);
@@ -105,7 +105,7 @@ void VPValue::dump() const {
 }
 
 void VPDef::dump() const {
-  const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
+  const VPRecipeBase *Instr = dyn_cast_if_present<VPRecipeBase>(this);
   VPSlotTracker SlotTracker(
       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
   print(dbgs(), "", SlotTracker);
@@ -1218,7 +1218,8 @@ void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
       auto *VPInst = cast<VPInstruction>(&VPI);
 
-      auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
+      auto *Inst =
+          dyn_cast_if_present<Instruction>(VPInst->getUnderlyingValue());
       if (!Inst)
         continue;
       auto *IG = IAI.getInterleaveGroup(Inst);
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h
index 94cb7688981361..7ca28120a30e79 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.h
+++ b/llvm/lib/Transforms/Vectorize/VPlan.h
@@ -2229,8 +2229,8 @@ class VPDerivedIVRecipe : public VPRecipeBase, public VPValue {
                     Type *TruncResultTy)
       : VPRecipeBase(VPDef::VPDerivedIVSC, {Start, CanonicalIV, Step}),
         VPValue(this), TruncResultTy(TruncResultTy), Kind(IndDesc.getKind()),
-        FPBinOp(dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp())) {
-  }
+        FPBinOp(
+            dyn_cast_if_present<FPMathOperator>(IndDesc.getInductionBinOp())) {}
 
   ~VPDerivedIVRecipe() override = default;
 
@@ -2279,7 +2279,7 @@ class VPScalarIVStepsRecipe : public VPRecipeWithIRFlags, public VPValue {
                         VPValue *Step)
       : VPScalarIVStepsRecipe(
             IV, Step, IndDesc.getInductionOpcode(),
-            dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp())
+            dyn_cast_if_present<FPMathOperator>(IndDesc.getInductionBinOp())
                 ? IndDesc.getInductionBinOp()->getFastMathFlags()
                 : FastMathFlags()) {}
 
diff --git a/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp b/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
index 02e400d590bed4..9fb4446c718bd6 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
@@ -66,8 +66,8 @@ bool VPRecipeBase::mayWriteToMemory() const {
   case VPWidenPHISC:
   case VPWidenSC:
   case VPWidenSelectSC: {
-    const Instruction *I =
-        dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
+    const Instruction *I = dyn_cast_if_present<Instruction>(
+        getVPSingleValue()->getUnderlyingValue());
     (void)I;
     assert((!I || !I->mayWriteToMemory()) &&
            "underlying instruction may write to memory");
@@ -100,8 +100,8 @@ bool VPRecipeBase::mayReadFromMemory() const {
   case VPWidenPHISC:
   case VPWidenSC:
   case VPWidenSelectSC: {
-    const Instruction *I =
-        dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
+    const Instruction *I = dyn_cast_if_present<Instruction>(
+        getVPSingleValue()->getUnderlyingValue());
     (void)I;
     assert((!I || !I->mayReadFromMemory()) &&
            "underlying instruction may read from memory");
@@ -141,8 +141,8 @@ bool VPRecipeBase::mayHaveSideEffects() const {
   case VPWidenPointerInductionSC:
   case VPWidenSC:
   case VPWidenSelectSC: {
-    const Instruction *I =
-        dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
+    const Instruction *I = dyn_cast_if_present<Instruction>(
+        getVPSingleValue()->getUnderlyingValue());
     (void)I;
     assert((!I || !I->mayHaveSideEffects()) &&
            "underlying instruction has side-effects");
@@ -608,7 +608,8 @@ void VPWidenSelectRecipe::execute(VPTransformState &State) {
     Value *Op1 = State.get(getOperand(2), Part);
     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
     State.set(this, Sel, Part);
-    State.addMetadata(Sel, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
+    State.addMetadata(Sel,
+                      dyn_cast_if_present<Instruction>(getUnderlyingValue()));
   }
 }
 
@@ -704,7 +705,8 @@ void VPWidenRecipe::execute(VPTransformState &State) {
 
       // Use this vector value for all users of the original instruction.
       State.set(this, V, Part);
-      State.addMetadata(V, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
+      State.addMetadata(V,
+                        dyn_cast_if_present<Instruction>(getUnderlyingValue()));
     }
 
     break;
@@ -729,14 +731,15 @@ void VPWidenRecipe::execute(VPTransformState &State) {
       if (FCmp) {
         // Propagate fast math flags.
         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
-        if (auto *I = dyn_cast_or_null<Instruction>(getUnderlyingValue()))
+        if (auto *I = dyn_cast_if_present<Instruction>(getUnderlyingValue()))
           Builder.setFastMathFlags(I->getFastMathFlags());
         C = Builder.CreateFCmp(getPredicate(), A, B);
       } else {
         C = Builder.CreateICmp(getPredicate(), A, B);
       }
       State.set(this, C, Part);
-      State.addMetadata(C, dyn_cast_or_null<Instruction>(getUnderlyingValue()));
+      State.addMetadata(C,
+                        dyn_cast_if_present<Instruction>(getUnderlyingValue()));
     }
 
     break;
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index 33132880d5a444..4ee5b5b12ee28e 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -223,12 +223,12 @@ static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan) {
     if (!Region1->isReplicator())
       continue;
     auto *MiddleBasicBlock =
-        dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
+        dyn_cast_if_present<VPBasicBlock>(Region1->getSingleSuccessor());
     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
       continue;
 
-    auto *Region2 =
-        dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
+    auto *Region2 = dyn_cast_if_present<VPRegionBlock>(
+        MiddleBasicBlock->getSingleSuccessor());
     if (!Region2 || !Region2->isReplicator())
       continue;
 
@@ -373,7 +373,7 @@ bool VPlanTransforms::mergeBlocksIntoPredecessors(VPlan &Plan) {
   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
            vp_depth_first_deep(Plan.getEntry()))) {
     auto *PredVPBB =
-        dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
+        dyn_cast_if_present<VPBasicBlock>(VPBB->getSinglePredecessor());
     if (PredVPBB && PredVPBB->getNumSuccessors() == 1)
       WorkList.push_back(VPBB);
   }
@@ -607,7 +607,8 @@ void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
 
 #ifndef NDEBUG
 static VPRegionBlock *GetReplicateRegion(VPRecipeBase *R) {
-  auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
+  auto *Region =
+      dyn_cast_if_present<VPRegionBlock>(R->getParent()->getParent());
   if (Region && Region->isReplicator()) {
     assert(Region->getNumSuccessors() == 1 &&
            Region->getNumPredecessors() == 1 && "Expected SESE region!");
@@ -722,7 +723,7 @@ bool VPlanTransforms::adjustFixedOrderRecurrences(VPlan &Plan,
     // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
     // to terminate.
     while (auto *PrevPhi =
-               dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
+               dyn_cast_if_present<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
       assert(PrevPhi->getParent() == FOR->getParent());
       assert(SeenPhis.insert(PrevPhi).second);
       Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
@@ -918,7 +919,7 @@ void VPlanTransforms::truncateToMinimalBitwidths(
         for (VPValue *Op : R.operands()) {
           if (!Op->isLiveIn())
             continue;
-          auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
+          auto *UV = dyn_cast_if_present<Instruction>(Op->getUnderlyingValue());
           if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
               all_of(Op->users(), [](VPUser *U) {
                 return !isa<VPWidenRecipe, VPWidenSelectRecipe>(U);
diff --git a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
index f18711ba30b708..5135c3d8800d8a 100644
--- a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
+++ b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
@@ -906,8 +906,8 @@ bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
 
   // Bail for single insertion if it is a load.
   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
-  auto *I0 = dyn_cast_or_null<Instruction>(V0);
-  auto *I1 = dyn_cast_or_null<Instruction>(V1);
+  auto *I0 = dyn_cast_if_present<Instruction>(V0);
+  auto *I1 = dyn_cast_if_present<Instruction>(V1);
   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
       (IsConst1 && I0 && I0->mayReadFromMemory()))
     return false;
diff --git a/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp b/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
index f4d8496aba4a7c..7dac43224d82dd 100644
--- a/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
+++ b/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
@@ -43,17 +43,17 @@ void identifyUninterestingMDNodes(Oracle &O, MDNodeList &MDs) {
       continue;
 
     // Determine if the current MDNode is DebugInfo
-    if (DINode *DIM = dyn_cast_or_null<DINode>(MD)) {
+    if (DINode *DIM = dyn_cast_if_present<DINode>(MD)) {
       // Scan operands and record attached tuples
       for (size_t I = 0; I < DIM->getNumOperands(); ++I)
-        if (MDTuple *MDT = dyn_cast_or_null<MDTuple>(DIM->getOperand(I)))
+        if (MDTuple *MDT = dyn_cast_if_present<MDTuple>(DIM->getOperand(I)))
           if (!Visited.count(MDT) && MDT->getNumOperands())
             Tuples.insert({DIM, I, MDT});
     }
 
     // Add all of the operands of the current node to the loop's todo list.
     for (Metadata *Op : MD->operands())
-      if (MDNode *OMD = dyn_cast_or_null<MDNode>(Op))
+      if (MDNode *OMD = dyn_cast_if_present<MDNode>(Op))
         ToLook.push_back(OMD);
 
     Visited.insert(MD);
diff --git a/llvm/tools/llvm-reduce/deltas/ReduceOpcodes.cpp b/llvm/tools/llvm-reduce/deltas/ReduceOpcodes.cpp
index f8fa83e9271335..9a5eada3c9515d 100644
--- a/llvm/tools/llvm-reduce/deltas/ReduceOpcodes.cpp
+++ b/llvm/tools/llvm-reduce/deltas/ReduceOpcodes.cpp
@@ -250,7 +250,7 @@ static void replaceOpcodesInModule(Oracle &O, ReducerWorkItem &WorkItem) {
     for (BasicBlock &BB : F)
       for (Instruction &I : make_early_inc_range(BB)) {
         Instruction *Replacement =
-            dyn_cast_or_null<Instruction>(reduceInstruction(O, Mod, I));
+            dyn_cast_if_present<Instruction>(reduceInstruction(O, Mod, I));
         if (Replacement && Replacement != &I) {
           if (isa<FPMathOperator>(Replacement))
             Replacement->copyFastMathFlags(&I);
diff --git a/llvm/unittests/Analysis/LoopInfoTest.cpp b/llvm/unittests/Analysis/LoopInfoTest.cpp
index 126467189d92dd..57b7a09eec0287 100644
--- a/llvm/unittests/Analysis/LoopInfoTest.cpp
+++ b/llvm/unittests/Analysis/LoopInfoTest.cpp
@@ -277,7 +277,7 @@ TEST(LoopInfoTest, CanonicalLoop) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -336,7 +336,7 @@ TEST(LoopInfoTest, LoopWithInverseGuardSuccs) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -395,7 +395,7 @@ TEST(LoopInfoTest, LoopWithSwappedGuardCmp) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -454,7 +454,7 @@ TEST(LoopInfoTest, LoopWithInverseLatchSuccs) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -513,7 +513,7 @@ TEST(LoopInfoTest, LoopWithLatchCmpNE) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -573,7 +573,7 @@ TEST(LoopInfoTest, LoopWithGuardCmpSLE) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ubPlusOne");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -688,7 +688,7 @@ TEST(LoopInfoTest, LoopUnsignedBounds) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_ULT);
@@ -745,7 +745,7 @@ TEST(LoopInfoTest, DecreasingLoop) {
         EXPECT_EQ(Bounds->getInitialIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_EQ(StepValue, nullptr);
         ConstantInt *FinalIVValue =
             dyn_cast<ConstantInt>(&Bounds->getFinalIVValue());
@@ -867,7 +867,7 @@ TEST(LoopInfoTest, ZextIndVar) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "indvars.iv.next");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "wide.trip.count");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_NE);
@@ -928,7 +928,7 @@ TEST(LoopInfoTest, MultiExitingLoop) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -988,7 +988,7 @@ TEST(LoopInfoTest, MultiExitLoop) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -1040,7 +1040,7 @@ TEST(LoopInfoTest, UnguardedLoop) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -1098,7 +1098,7 @@ TEST(LoopInfoTest, UnguardedLoopWithControlFlow) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -1169,7 +1169,7 @@ TEST(LoopInfoTest, LoopNest) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc.outer");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -1194,7 +1194,8 @@ TEST(LoopInfoTest, LoopNest) {
             dyn_cast<ConstantInt>(&InnerBounds->getInitialIVValue());
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(InnerBounds->getStepInst().getName(), "inc");
-        StepValue = dyn_cast_or_null<ConstantInt>(InnerBounds->getStepValue());
+        StepValue =
+            dyn_cast_if_present<ConstantInt>(InnerBounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(InnerBounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(InnerBounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
@@ -1262,7 +1263,7 @@ TEST(LoopInfoTest, AuxiliaryIV) {
         EXPECT_TRUE(InitialIVValue && InitialIVValue->isZero());
         EXPECT_EQ(Bounds->getStepInst().getName(), "inc");
         ConstantInt *StepValue =
-            dyn_cast_or_null<ConstantInt>(Bounds->getStepValue());
+            dyn_cast_if_present<ConstantInt>(Bounds->getStepValue());
         EXPECT_TRUE(StepValue && StepValue->isOne());
         EXPECT_EQ(Bounds->getFinalIVValue().getName(), "ub");
         EXPECT_EQ(Bounds->getCanonicalPredicate(), ICmpInst::ICMP_SLT);
diff --git a/llvm/unittests/Analysis/MemorySSATest.cpp b/llvm/unittests/Analysis/MemorySSATest.cpp
index 4c157d5bedfc28..d09dd111acf80d 100644
--- a/llvm/unittests/Analysis/MemorySSATest.cpp
+++ b/llvm/unittests/Analysis/MemorySSATest.cpp
@@ -1011,7 +1011,7 @@ TEST_F(MemorySSATest, TestStoreMustAlias) {
 
   unsigned I = 0;
   for (StoreInst *V : {SA1, SB1, SA2, SB2, SA3, SB3}) {
-    MemoryDef *MemDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(V));
+    MemoryDef *MemDef = dyn_cast_if_present<MemoryDef>(MSSA.getMemoryAccess(V));
     EXPECT_EQ(MemDef->isOptimized(), false)
         << "Store " << I << " is optimized from the start?";
     if (V == SA1)
@@ -1063,7 +1063,7 @@ TEST_F(MemorySSATest, TestStoreMayAlias) {
 
   unsigned I = 0;
   for (StoreInst *V : Sts) {
-    MemoryDef *MemDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(V));
+    MemoryDef *MemDef = dyn_cast_if_present<MemoryDef>(MSSA.getMemoryAccess(V));
     EXPECT_EQ(MemDef->isOptimized(), false)
         << "Store " << I << " is optimized from the start?";
     ++I;
@@ -1074,7 +1074,7 @@ TEST_F(MemorySSATest, TestStoreMayAlias) {
 
   I = 0;
   for (StoreInst *V : Sts) {
-    MemoryDef *MemDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(V));
+    MemoryDef *MemDef = dyn_cast_if_present<MemoryDef>(MSSA.getMemoryAccess(V));
     EXPECT_EQ(MemDef->isOptimized(), true)
         << "Store " << I << " was not optimized";
     // EXPECT_EQ expands such that if we increment I above, it won't get
diff --git a/llvm/unittests/Analysis/VectorFunctionABITest.cpp b/llvm/unittests/Analysis/VectorFunctionABITest.cpp
index 201dd1127ef234..157dfa80a2f93a 100644
--- a/llvm/unittests/Analysis/VectorFunctionABITest.cpp
+++ b/llvm/unittests/Analysis/VectorFunctionABITest.cpp
@@ -707,7 +707,7 @@ define void @call(void () * %f) {
   ret void
 }
 )IR");
-  auto *F = dyn_cast_or_null<Function>(M->getNamedValue("call"));
+  auto *F = dyn_cast_if_present<Function>(M->getNamedValue("call"));
   ASSERT_TRUE(F);
   auto *CI = dyn_cast<CallInst>(&F->front().front());
   ASSERT_TRUE(CI);
diff --git a/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp b/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
index 32319f1e97587f..779670c1ee4640 100644
--- a/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
+++ b/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
@@ -96,7 +96,8 @@ TEST_F(AsmPrinterEmitDwarfSymbolReferenceTest, ELFDWARF32) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfSymbolReference(Val, false);
 
-  const MCSymbolRefExpr *ActualArg0 = dyn_cast_or_null<MCSymbolRefExpr>(Arg0);
+  const MCSymbolRefExpr *ActualArg0 =
+      dyn_cast_if_present<MCSymbolRefExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(&(ActualArg0->getSymbol()), Val);
 }
@@ -119,7 +120,8 @@ TEST_F(AsmPrinterEmitDwarfSymbolReferenceTest, ELFDWARF64) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfSymbolReference(Val, false);
 
-  const MCSymbolRefExpr *ActualArg0 = dyn_cast_or_null<MCSymbolRefExpr>(Arg0);
+  const MCSymbolRefExpr *ActualArg0 =
+      dyn_cast_if_present<MCSymbolRefExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(&(ActualArg0->getSymbol()), Val);
 }
@@ -158,7 +160,8 @@ TEST_F(AsmPrinterEmitDwarfStringOffsetTest, DWARF32) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfStringOffset(Val);
 
-  const MCSymbolRefExpr *ActualArg0 = dyn_cast_or_null<MCSymbolRefExpr>(Arg0);
+  const MCSymbolRefExpr *ActualArg0 =
+      dyn_cast_if_present<MCSymbolRefExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(&(ActualArg0->getSymbol()), Val.Symbol);
 }
@@ -182,7 +185,8 @@ TEST_F(AsmPrinterEmitDwarfStringOffsetTest, DWARF64) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfStringOffset(Val);
 
-  const MCSymbolRefExpr *ActualArg0 = dyn_cast_or_null<MCSymbolRefExpr>(Arg0);
+  const MCSymbolRefExpr *ActualArg0 =
+      dyn_cast_if_present<MCSymbolRefExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(&(ActualArg0->getSymbol()), Val.Symbol);
 }
@@ -221,17 +225,17 @@ TEST_F(AsmPrinterEmitDwarfOffsetTest, DWARF32) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfOffset(Label, Offset);
 
-  const MCBinaryExpr *ActualArg0 = dyn_cast_or_null<MCBinaryExpr>(Arg0);
+  const MCBinaryExpr *ActualArg0 = dyn_cast_if_present<MCBinaryExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(ActualArg0->getOpcode(), MCBinaryExpr::Add);
 
   const MCSymbolRefExpr *ActualLHS =
-      dyn_cast_or_null<MCSymbolRefExpr>(ActualArg0->getLHS());
+      dyn_cast_if_present<MCSymbolRefExpr>(ActualArg0->getLHS());
   ASSERT_NE(ActualLHS, nullptr);
   EXPECT_EQ(&(ActualLHS->getSymbol()), Label);
 
   const MCConstantExpr *ActualRHS =
-      dyn_cast_or_null<MCConstantExpr>(ActualArg0->getRHS());
+      dyn_cast_if_present<MCConstantExpr>(ActualArg0->getRHS());
   ASSERT_NE(ActualRHS, nullptr);
   EXPECT_EQ(static_cast<uint64_t>(ActualRHS->getValue()), Offset);
 }
@@ -245,17 +249,17 @@ TEST_F(AsmPrinterEmitDwarfOffsetTest, DWARF64) {
       .WillOnce(SaveArg<0>(&Arg0));
   TestPrinter->getAP()->emitDwarfOffset(Label, Offset);
 
-  const MCBinaryExpr *ActualArg0 = dyn_cast_or_null<MCBinaryExpr>(Arg0);
+  const MCBinaryExpr *ActualArg0 = dyn_cast_if_present<MCBinaryExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(ActualArg0->getOpcode(), MCBinaryExpr::Add);
 
   const MCSymbolRefExpr *ActualLHS =
-      dyn_cast_or_null<MCSymbolRefExpr>(ActualArg0->getLHS());
+      dyn_cast_if_present<MCSymbolRefExpr>(ActualArg0->getLHS());
   ASSERT_NE(ActualLHS, nullptr);
   EXPECT_EQ(&(ActualLHS->getSymbol()), Label);
 
   const MCConstantExpr *ActualRHS =
-      dyn_cast_or_null<MCConstantExpr>(ActualArg0->getRHS());
+      dyn_cast_if_present<MCConstantExpr>(ActualArg0->getRHS());
   ASSERT_NE(ActualRHS, nullptr);
   EXPECT_EQ(static_cast<uint64_t>(ActualRHS->getValue()), Offset);
 }
diff --git a/llvm/unittests/CodeGen/DIETest.cpp b/llvm/unittests/CodeGen/DIETest.cpp
index 87dbb63e8f16d3..4121a7a5fad36f 100644
--- a/llvm/unittests/CodeGen/DIETest.cpp
+++ b/llvm/unittests/CodeGen/DIETest.cpp
@@ -99,7 +99,8 @@ TEST_P(DIELabelFixture, EmitValue) {
       .WillOnce(SaveArg<0>(&Arg0));
   Tst.emitValue(TestPrinter->getAP(), Form);
 
-  const MCSymbolRefExpr *ActualArg0 = dyn_cast_or_null<MCSymbolRefExpr>(Arg0);
+  const MCSymbolRefExpr *ActualArg0 =
+      dyn_cast_if_present<MCSymbolRefExpr>(Arg0);
   ASSERT_NE(ActualArg0, nullptr);
   EXPECT_EQ(&(ActualArg0->getSymbol()), Val);
 }
diff --git a/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp b/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
index e79d0bb2f65aea..71cd21865d0aad 100644
--- a/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ b/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -3264,21 +3264,22 @@ TEST_F(OpenMPIRBuilderTest, CopyinBlocks) {
   OMPBuilder.createCopyinClauseBlocks(Builder.saveIP(), MasterAddress,
                                       PrivAddress, Int32, /*BranchtoEnd*/ true);
 
-  BranchInst *EntryBr = dyn_cast_or_null<BranchInst>(EntryBB->getTerminator());
+  BranchInst *EntryBr =
+      dyn_cast_if_present<BranchInst>(EntryBB->getTerminator());
 
   EXPECT_NE(EntryBr, nullptr);
   EXPECT_TRUE(EntryBr->isConditional());
 
   BasicBlock *NotMasterBB = EntryBr->getSuccessor(0);
   BasicBlock *CopyinEnd = EntryBr->getSuccessor(1);
-  CmpInst *CMP = dyn_cast_or_null<CmpInst>(EntryBr->getCondition());
+  CmpInst *CMP = dyn_cast_if_present<CmpInst>(EntryBr->getCondition());
 
   EXPECT_NE(CMP, nullptr);
   EXPECT_NE(NotMasterBB, nullptr);
   EXPECT_NE(CopyinEnd, nullptr);
 
   BranchInst *NotMasterBr =
-      dyn_cast_or_null<BranchInst>(NotMasterBB->getTerminator());
+      dyn_cast_if_present<BranchInst>(NotMasterBB->getTerminator());
   EXPECT_NE(NotMasterBr, nullptr);
   EXPECT_FALSE(NotMasterBr->isConditional());
   EXPECT_EQ(CopyinEnd, NotMasterBr->getSuccessor(0));
@@ -4908,9 +4909,9 @@ TEST_F(OpenMPIRBuilderTest, CreateReductions) {
 
   // Check that the values stored into the local array are privatized reduction
   // variables.
-  auto *FirstPrivatized = dyn_cast_or_null<AllocaInst>(
+  auto *FirstPrivatized = dyn_cast_if_present<AllocaInst>(
       findStoredValue<GetElementPtrInst>(FirstArrayElemPtr));
-  auto *SecondPrivatized = dyn_cast_or_null<AllocaInst>(
+  auto *SecondPrivatized = dyn_cast_if_present<AllocaInst>(
       findStoredValue<GetElementPtrInst>(SecondArrayElemPtr));
   ASSERT_NE(FirstPrivatized, nullptr);
   ASSERT_NE(SecondPrivatized, nullptr);
@@ -6530,9 +6531,9 @@ TEST_F(OpenMPIRBuilderTest, CreateTaskgroupWithTasks) {
   ASSERT_EQ(TaskAllocFn->getNumUses(), 2u);
 
   CallInst *FirstTaskAllocCall =
-      dyn_cast_or_null<CallInst>(*TaskAllocFn->users().begin());
+      dyn_cast_if_present<CallInst>(*TaskAllocFn->users().begin());
   CallInst *SecondTaskAllocCall =
-      dyn_cast_or_null<CallInst>(*TaskAllocFn->users().begin()++);
+      dyn_cast_if_present<CallInst>(*TaskAllocFn->users().begin()++);
   ASSERT_NE(FirstTaskAllocCall, nullptr);
   ASSERT_NE(SecondTaskAllocCall, nullptr);
 
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index d15ff9dd51a4c4..021213e6e8f34b 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -966,7 +966,7 @@ TEST_F(IRBuilderTest, appendDebugInfo) {
     for (auto *IE : CU->getImportedEntities())
       Names.push_back(IE->getName());
     for (auto *Node : CU->getMacros())
-      if (auto *MN = dyn_cast_or_null<DIMacro>(Node))
+      if (auto *MN = dyn_cast_if_present<DIMacro>(Node))
         Names.push_back(MN->getName());
     return Names;
   };
diff --git a/llvm/unittests/IR/MetadataTest.cpp b/llvm/unittests/IR/MetadataTest.cpp
index 1570631287b2a7..64bc29560372a0 100644
--- a/llvm/unittests/IR/MetadataTest.cpp
+++ b/llvm/unittests/IR/MetadataTest.cpp
@@ -1618,17 +1618,18 @@ TEST_F(DIGenericSubrangeTest, fortranAssumedRankInt) {
   auto Lower = N->getLowerBound();
   ASSERT_TRUE(Lower);
   ASSERT_TRUE(isa<DIExpression *>(Lower));
-  EXPECT_EQ(dyn_cast_or_null<DIExpression>(LI), cast<DIExpression *>(Lower));
+  EXPECT_EQ(dyn_cast_if_present<DIExpression>(LI), cast<DIExpression *>(Lower));
 
   auto Upper = N->getUpperBound();
   ASSERT_TRUE(Upper);
   ASSERT_TRUE(isa<DIExpression *>(Upper));
-  EXPECT_EQ(dyn_cast_or_null<DIExpression>(UI), cast<DIExpression *>(Upper));
+  EXPECT_EQ(dyn_cast_if_present<DIExpression>(UI), cast<DIExpression *>(Upper));
 
   auto Stride = N->getStride();
   ASSERT_TRUE(Stride);
   ASSERT_TRUE(isa<DIExpression *>(Stride));
-  EXPECT_EQ(dyn_cast_or_null<DIExpression>(SI), cast<DIExpression *>(Stride));
+  EXPECT_EQ(dyn_cast_if_present<DIExpression>(SI),
+            cast<DIExpression *>(Stride));
 
   EXPECT_EQ(N, DIGenericSubrange::get(Context, nullptr, LI, UI, SI));
 
diff --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp
index a9256548145986..e093b28250d067 100644
--- a/llvm/unittests/Support/Casting.cpp
+++ b/llvm/unittests/Support/Casting.cpp
@@ -70,7 +70,7 @@ foo *bar::caz() { return cast_or_null<foo>(this); }
 
 foo *bar::daz() { return dyn_cast<foo>(this); }
 
-foo *bar::naz() { return dyn_cast_or_null<foo>(this); }
+foo *bar::naz() { return dyn_cast_if_present<foo>(this); }
 
 bar *fub();
 
@@ -233,13 +233,13 @@ TEST(CastingTest, dyn_cast) {
 // All these tests forward to dyn_cast_if_present, so they also provde an
 // effective test for its use cases.
 TEST(CastingTest, dyn_cast_or_null) {
-  const foo *F1 = dyn_cast_or_null<foo>(B2);
+  const foo *F1 = dyn_cast_if_present<foo>(B2);
   EXPECT_NE(F1, null_foo);
-  const foo *F2 = dyn_cast_or_null<foo>(B2);
+  const foo *F2 = dyn_cast_if_present<foo>(B2);
   EXPECT_NE(F2, null_foo);
-  const foo *F3 = dyn_cast_or_null<foo>(B4);
+  const foo *F3 = dyn_cast_if_present<foo>(B4);
   EXPECT_NE(F3, null_foo);
-  foo *F4 = dyn_cast_or_null<foo>(fub());
+  foo *F4 = dyn_cast_if_present<foo>(fub());
   EXPECT_EQ(F4, null_foo);
   foo *F5 = B1.naz();
   EXPECT_NE(F5, null_foo);
@@ -503,12 +503,12 @@ TEST(CastingTest, smart_dyn_cast) {
 }
 
 TEST(CastingTest, smart_dyn_cast_or_null) {
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(MN), nullptr);
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(CN), nullptr);
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(MB), nullptr);
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(CB), nullptr);
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(MD), &D);
-  EXPECT_EQ(dyn_cast_or_null<pointer_wrappers::Derived>(CD), &D);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(MN), nullptr);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(CN), nullptr);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(MB), nullptr);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(CB), nullptr);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(MD), &D);
+  EXPECT_EQ(dyn_cast_if_present<pointer_wrappers::Derived>(CD), &D);
 }
 
 } // end namespace pointer_wrappers
diff --git a/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp b/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
index b75a492c58bc40..b7892a54e940aa 100644
--- a/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
+++ b/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
@@ -88,17 +88,17 @@ TEST(SSAUpdaterBulk, SimpleMerge) {
   Updater.RewriteAllUses(&DT);
 
   // Check how %5 and %6 were rewritten.
-  PHINode *UpdatePhiA = dyn_cast_or_null<PHINode>(I1->getOperand(0));
+  PHINode *UpdatePhiA = dyn_cast_if_present<PHINode>(I1->getOperand(0));
   EXPECT_NE(UpdatePhiA, nullptr);
   EXPECT_EQ(UpdatePhiA->getIncomingValueForBlock(TrueBB), AddOp1);
   EXPECT_EQ(UpdatePhiA->getIncomingValueForBlock(FalseBB), AddOp2);
-  EXPECT_EQ(UpdatePhiA, dyn_cast_or_null<PHINode>(I1->getOperand(0)));
+  EXPECT_EQ(UpdatePhiA, dyn_cast_if_present<PHINode>(I1->getOperand(0)));
 
   // Check how %7 was rewritten.
-  PHINode *UpdatePhiB = dyn_cast_or_null<PHINode>(I3->getOperand(0));
+  PHINode *UpdatePhiB = dyn_cast_if_present<PHINode>(I3->getOperand(0));
   EXPECT_EQ(UpdatePhiB->getIncomingValueForBlock(TrueBB), SubOp1);
   EXPECT_EQ(UpdatePhiB->getIncomingValueForBlock(FalseBB), SubOp2);
-  EXPECT_EQ(UpdatePhiB, dyn_cast_or_null<PHINode>(I3->getOperand(1)));
+  EXPECT_EQ(UpdatePhiB, dyn_cast_if_present<PHINode>(I3->getOperand(1)));
 
   // Check that %8 was kept untouched.
   EXPECT_EQ(I4->getOperand(0), SubOp1);
@@ -187,7 +187,7 @@ TEST(SSAUpdaterBulk, Irreducible) {
   EXPECT_EQ(Return->getOperand(0), FirstArg);
 
   // I2 should use the new phi.
-  PHINode *UpdatePhi = dyn_cast_or_null<PHINode>(I2->getOperand(0));
+  PHINode *UpdatePhi = dyn_cast_if_present<PHINode>(I2->getOperand(0));
   EXPECT_NE(UpdatePhi, nullptr);
   EXPECT_EQ(UpdatePhi->getIncomingValueForBlock(LoopStartBB), AddOp2);
   EXPECT_EQ(UpdatePhi->getIncomingValueForBlock(IfBB), UndefValue::get(I32Ty));
diff --git a/llvm/utils/TableGen/CodeEmitterGen.cpp b/llvm/utils/TableGen/CodeEmitterGen.cpp
index 48ed319bf06f47..8f943b345568fe 100644
--- a/llvm/utils/TableGen/CodeEmitterGen.cpp
+++ b/llvm/utils/TableGen/CodeEmitterGen.cpp
@@ -282,7 +282,7 @@ CodeEmitterGen::getInstructionCases(Record *R, CodeGenTarget &Target) {
   };
 
   if (const RecordVal *RV = R->getValue("EncodingInfos")) {
-    if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+    if (auto *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
       const CodeGenHwModes &HWM = Target.getHwModes();
       EncodingInfoByHwMode EBM(DI->getDef(), HWM);
       append("      switch (HwMode) {\n");
@@ -374,7 +374,7 @@ void CodeEmitterGen::emitInstructionBaseValues(
 
     Record *EncodingDef = R;
     if (const RecordVal *RV = R->getValue("EncodingInfos")) {
-      if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+      if (auto *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
         EncodingInfoByHwMode EBM(DI->getDef(), HWM);
         if (EBM.hasMode(HwMode))
           EncodingDef = EBM.get(HwMode);
@@ -444,7 +444,7 @@ void CodeEmitterGen::run(raw_ostream &o) {
         continue;
 
       if (const RecordVal *RV = R->getValue("EncodingInfos")) {
-        if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+        if (DefInit *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
           EncodingInfoByHwMode EBM(DI->getDef(), HWM);
           for (auto &KV : EBM) {
             BitsInit *BI = KV.second->getValueAsBitsInit("Inst");
diff --git a/llvm/utils/TableGen/CodeGenInstAlias.cpp b/llvm/utils/TableGen/CodeGenInstAlias.cpp
index 8634d45eafc707..726419ba6011ef 100644
--- a/llvm/utils/TableGen/CodeGenInstAlias.cpp
+++ b/llvm/utils/TableGen/CodeGenInstAlias.cpp
@@ -123,7 +123,7 @@ bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
     if (!BI->isComplete())
       return false;
     // Convert the bits init to an integer and use that for the result.
-    IntInit *II = dyn_cast_or_null<IntInit>(
+    IntInit *II = dyn_cast_if_present<IntInit>(
         BI->convertInitializerTo(IntRecTy::get(BI->getRecordKeeper())));
     if (!II)
       return false;
diff --git a/llvm/utils/TableGen/CodeGenRegisters.cpp b/llvm/utils/TableGen/CodeGenRegisters.cpp
index d1abdb74ea4a98..77af0cceb50329 100644
--- a/llvm/utils/TableGen/CodeGenRegisters.cpp
+++ b/llvm/utils/TableGen/CodeGenRegisters.cpp
@@ -786,7 +786,7 @@ CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
   Namespace = R->getValueAsString("Namespace");
 
   if (const RecordVal *RV = R->getValue("RegInfos"))
-    if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
+    if (DefInit *DI = dyn_cast_if_present<DefInit>(RV->getValue()))
       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
   unsigned Size = R->getValueAsInt("Size");
   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
diff --git a/llvm/utils/TableGen/DecoderEmitter.cpp b/llvm/utils/TableGen/DecoderEmitter.cpp
index 607f19653c7a0d..1561a616d58d4d 100644
--- a/llvm/utils/TableGen/DecoderEmitter.cpp
+++ b/llvm/utils/TableGen/DecoderEmitter.cpp
@@ -2443,7 +2443,7 @@ void DecoderEmitter::run(raw_ostream &o) {
 
     if (const RecordVal *RV =
             NumberedInstruction->TheDef->getValue("EncodingInfos")) {
-      if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+      if (auto *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
         const CodeGenHwModes &HWM = Target.getHwModes();
         EncodingInfoByHwMode EBM(DI->getDef(), HWM);
         for (auto &KV : EBM)
@@ -2461,7 +2461,7 @@ void DecoderEmitter::run(raw_ostream &o) {
 
     if (const RecordVal *RV =
             NumberedInstruction->TheDef->getValue("EncodingInfos")) {
-      if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+      if (DefInit *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
         const CodeGenHwModes &HWM = Target.getHwModes();
         EncodingInfoByHwMode EBM(DI->getDef(), HWM);
         for (auto &KV : EBM) {
diff --git a/llvm/utils/TableGen/VarLenCodeEmitterGen.cpp b/llvm/utils/TableGen/VarLenCodeEmitterGen.cpp
index bfb7e5c333170c..f9c88f8a447eb8 100644
--- a/llvm/utils/TableGen/VarLenCodeEmitterGen.cpp
+++ b/llvm/utils/TableGen/VarLenCodeEmitterGen.cpp
@@ -235,7 +235,7 @@ void VarLenCodeEmitterGen::run(raw_ostream &OS) {
 
     // Setup alternative encodings according to HwModes
     if (const RecordVal *RV = R->getValue("EncodingInfos")) {
-      if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
+      if (auto *DI = dyn_cast_if_present<DefInit>(RV->getValue())) {
         const CodeGenHwModes &HWM = Target.getHwModes();
         EncodingInfoByHwMode EBM(DI->getDef(), HWM);
         for (auto &KV : EBM) {



More information about the llvm-commits mailing list