Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/GenericDomTree.h
Warning:line 494, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name X86FlagsCopyLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp

1//====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
11/// flag bits.
12///
13/// We have to do this by carefully analyzing and rewriting the usage of the
14/// copied EFLAGS register because there is no general way to rematerialize the
15/// entire EFLAGS register safely and efficiently. Using `popf` both forces
16/// dynamic stack adjustment and can create correctness issues due to IF, TF,
17/// and other non-status flags being overwritten. Using sequences involving
18/// SAHF don't work on all x86 processors and are often quite slow compared to
19/// directly testing a single status preserved in its own GPR.
20///
21//===----------------------------------------------------------------------===//
22
23#include "X86.h"
24#include "X86InstrBuilder.h"
25#include "X86InstrInfo.h"
26#include "X86Subtarget.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/ScopeExit.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/SparseBitVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/MachineBasicBlock.h"
38#include "llvm/CodeGen/MachineConstantPool.h"
39#include "llvm/CodeGen/MachineDominators.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineModuleInfo.h"
45#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/MachineRegisterInfo.h"
47#include "llvm/CodeGen/MachineSSAUpdater.h"
48#include "llvm/CodeGen/TargetInstrInfo.h"
49#include "llvm/CodeGen/TargetRegisterInfo.h"
50#include "llvm/CodeGen/TargetSchedule.h"
51#include "llvm/CodeGen/TargetSubtargetInfo.h"
52#include "llvm/IR/DebugLoc.h"
53#include "llvm/MC/MCSchedule.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
58#include <algorithm>
59#include <cassert>
60#include <iterator>
61#include <utility>
62
63using namespace llvm;
64
65#define PASS_KEY"x86-flags-copy-lowering" "x86-flags-copy-lowering"
66#define DEBUG_TYPE"x86-flags-copy-lowering" PASS_KEY"x86-flags-copy-lowering"
67
68STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated")static llvm::Statistic NumCopiesEliminated = {"x86-flags-copy-lowering"
, "NumCopiesEliminated", "Number of copies of EFLAGS eliminated"
}
;
69STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted")static llvm::Statistic NumSetCCsInserted = {"x86-flags-copy-lowering"
, "NumSetCCsInserted", "Number of setCC instructions inserted"
}
;
70STATISTIC(NumTestsInserted, "Number of test instructions inserted")static llvm::Statistic NumTestsInserted = {"x86-flags-copy-lowering"
, "NumTestsInserted", "Number of test instructions inserted"}
;
71STATISTIC(NumAddsInserted, "Number of adds instructions inserted")static llvm::Statistic NumAddsInserted = {"x86-flags-copy-lowering"
, "NumAddsInserted", "Number of adds instructions inserted"}
;
72
73namespace {
74
75// Convenient array type for storing registers associated with each condition.
76using CondRegArray = std::array<unsigned, X86::LAST_VALID_COND + 1>;
77
78class X86FlagsCopyLoweringPass : public MachineFunctionPass {
79public:
80 X86FlagsCopyLoweringPass() : MachineFunctionPass(ID) { }
81
82 StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }
83 bool runOnMachineFunction(MachineFunction &MF) override;
84 void getAnalysisUsage(AnalysisUsage &AU) const override;
85
86 /// Pass identification, replacement for typeid.
87 static char ID;
88
89private:
90 MachineRegisterInfo *MRI = nullptr;
91 const X86Subtarget *Subtarget = nullptr;
92 const X86InstrInfo *TII = nullptr;
93 const TargetRegisterInfo *TRI = nullptr;
94 const TargetRegisterClass *PromoteRC = nullptr;
95 MachineDominatorTree *MDT = nullptr;
96
97 CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,
98 MachineBasicBlock::iterator CopyDefI);
99
100 Register promoteCondToReg(MachineBasicBlock &MBB,
101 MachineBasicBlock::iterator TestPos,
102 const DebugLoc &TestLoc, X86::CondCode Cond);
103 std::pair<unsigned, bool> getCondOrInverseInReg(
104 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
105 const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs);
106 void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
107 const DebugLoc &Loc, unsigned Reg);
108
109 void rewriteArithmetic(MachineBasicBlock &TestMBB,
110 MachineBasicBlock::iterator TestPos,
111 const DebugLoc &TestLoc, MachineInstr &MI,
112 MachineOperand &FlagUse, CondRegArray &CondRegs);
113 void rewriteCMov(MachineBasicBlock &TestMBB,
114 MachineBasicBlock::iterator TestPos, const DebugLoc &TestLoc,
115 MachineInstr &CMovI, MachineOperand &FlagUse,
116 CondRegArray &CondRegs);
117 void rewriteFCMov(MachineBasicBlock &TestMBB,
118 MachineBasicBlock::iterator TestPos,
119 const DebugLoc &TestLoc, MachineInstr &CMovI,
120 MachineOperand &FlagUse, CondRegArray &CondRegs);
121 void rewriteCondJmp(MachineBasicBlock &TestMBB,
122 MachineBasicBlock::iterator TestPos,
123 const DebugLoc &TestLoc, MachineInstr &JmpI,
124 CondRegArray &CondRegs);
125 void rewriteCopy(MachineInstr &MI, MachineOperand &FlagUse,
126 MachineInstr &CopyDefI);
127 void rewriteSetCC(MachineBasicBlock &TestMBB,
128 MachineBasicBlock::iterator TestPos,
129 const DebugLoc &TestLoc, MachineInstr &SetCCI,
130 MachineOperand &FlagUse, CondRegArray &CondRegs);
131};
132
133} // end anonymous namespace
134
135INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass, DEBUG_TYPE,static void *initializeX86FlagsCopyLoweringPassPassOnce(PassRegistry
&Registry) {
136 "X86 EFLAGS copy lowering", false, false)static void *initializeX86FlagsCopyLoweringPassPassOnce(PassRegistry
&Registry) {
137INITIALIZE_PASS_END(X86FlagsCopyLoweringPass, DEBUG_TYPE,PassInfo *PI = new PassInfo( "X86 EFLAGS copy lowering", "x86-flags-copy-lowering"
, &X86FlagsCopyLoweringPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<X86FlagsCopyLoweringPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeX86FlagsCopyLoweringPassPassFlag
; void llvm::initializeX86FlagsCopyLoweringPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeX86FlagsCopyLoweringPassPassFlag
, initializeX86FlagsCopyLoweringPassPassOnce, std::ref(Registry
)); }
138 "X86 EFLAGS copy lowering", false, false)PassInfo *PI = new PassInfo( "X86 EFLAGS copy lowering", "x86-flags-copy-lowering"
, &X86FlagsCopyLoweringPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<X86FlagsCopyLoweringPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeX86FlagsCopyLoweringPassPassFlag
; void llvm::initializeX86FlagsCopyLoweringPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeX86FlagsCopyLoweringPassPassFlag
, initializeX86FlagsCopyLoweringPassPassOnce, std::ref(Registry
)); }
139
140FunctionPass *llvm::createX86FlagsCopyLoweringPass() {
141 return new X86FlagsCopyLoweringPass();
142}
143
144char X86FlagsCopyLoweringPass::ID = 0;
145
146void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.addRequired<MachineDominatorTree>();
148 MachineFunctionPass::getAnalysisUsage(AU);
149}
150
151namespace {
152/// An enumeration of the arithmetic instruction mnemonics which have
153/// interesting flag semantics.
154///
155/// We can map instruction opcodes into these mnemonics to make it easy to
156/// dispatch with specific functionality.
157enum class FlagArithMnemonic {
158 ADC,
159 ADCX,
160 ADOX,
161 RCL,
162 RCR,
163 SBB,
164 SETB,
165};
166} // namespace
167
168static FlagArithMnemonic getMnemonicFromOpcode(unsigned Opcode) {
169 switch (Opcode) {
170 default:
171 report_fatal_error("No support for lowering a copy into EFLAGS when used "
172 "by this instruction!");
173
174#define LLVM_EXPAND_INSTR_SIZES(MNEMONIC, SUFFIX) \
175 case X86::MNEMONIC##8##SUFFIX: \
176 case X86::MNEMONIC##16##SUFFIX: \
177 case X86::MNEMONIC##32##SUFFIX: \
178 case X86::MNEMONIC##64##SUFFIX:
179
180#define LLVM_EXPAND_ADC_SBB_INSTR(MNEMONIC) \
181 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr) \
182 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr_REV) \
183 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rm) \
184 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, mr) \
185 case X86::MNEMONIC##8ri: \
186 case X86::MNEMONIC##16ri8: \
187 case X86::MNEMONIC##32ri8: \
188 case X86::MNEMONIC##64ri8: \
189 case X86::MNEMONIC##16ri: \
190 case X86::MNEMONIC##32ri: \
191 case X86::MNEMONIC##64ri32: \
192 case X86::MNEMONIC##8mi: \
193 case X86::MNEMONIC##16mi8: \
194 case X86::MNEMONIC##32mi8: \
195 case X86::MNEMONIC##64mi8: \
196 case X86::MNEMONIC##16mi: \
197 case X86::MNEMONIC##32mi: \
198 case X86::MNEMONIC##64mi32: \
199 case X86::MNEMONIC##8i8: \
200 case X86::MNEMONIC##16i16: \
201 case X86::MNEMONIC##32i32: \
202 case X86::MNEMONIC##64i32:
203
204 LLVM_EXPAND_ADC_SBB_INSTR(ADC)
205 return FlagArithMnemonic::ADC;
206
207 LLVM_EXPAND_ADC_SBB_INSTR(SBB)
208 return FlagArithMnemonic::SBB;
209
210#undef LLVM_EXPAND_ADC_SBB_INSTR
211
212 LLVM_EXPAND_INSTR_SIZES(RCL, rCL)
213 LLVM_EXPAND_INSTR_SIZES(RCL, r1)
214 LLVM_EXPAND_INSTR_SIZES(RCL, ri)
215 return FlagArithMnemonic::RCL;
216
217 LLVM_EXPAND_INSTR_SIZES(RCR, rCL)
218 LLVM_EXPAND_INSTR_SIZES(RCR, r1)
219 LLVM_EXPAND_INSTR_SIZES(RCR, ri)
220 return FlagArithMnemonic::RCR;
221
222#undef LLVM_EXPAND_INSTR_SIZES
223
224 case X86::ADCX32rr:
225 case X86::ADCX64rr:
226 case X86::ADCX32rm:
227 case X86::ADCX64rm:
228 return FlagArithMnemonic::ADCX;
229
230 case X86::ADOX32rr:
231 case X86::ADOX64rr:
232 case X86::ADOX32rm:
233 case X86::ADOX64rm:
234 return FlagArithMnemonic::ADOX;
235
236 case X86::SETB_C32r:
237 case X86::SETB_C64r:
238 return FlagArithMnemonic::SETB;
239 }
240}
241
242static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,
243 MachineInstr &SplitI,
244 const X86InstrInfo &TII) {
245 MachineFunction &MF = *MBB.getParent();
246
247 assert(SplitI.getParent() == &MBB &&((void)0)
248 "Split instruction must be in the split block!")((void)0);
249 assert(SplitI.isBranch() &&((void)0)
250 "Only designed to split a tail of branch instructions!")((void)0);
251 assert(X86::getCondFromBranch(SplitI) != X86::COND_INVALID &&((void)0)
252 "Must split on an actual jCC instruction!")((void)0);
253
254 // Dig out the previous instruction to the split point.
255 MachineInstr &PrevI = *std::prev(SplitI.getIterator());
256 assert(PrevI.isBranch() && "Must split after a branch!")((void)0);
257 assert(X86::getCondFromBranch(PrevI) != X86::COND_INVALID &&((void)0)
258 "Must split after an actual jCC instruction!")((void)0);
259 assert(!std::prev(PrevI.getIterator())->isTerminator() &&((void)0)
260 "Must only have this one terminator prior to the split!")((void)0);
261
262 // Grab the one successor edge that will stay in `MBB`.
263 MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(0).getMBB();
264
265 // Analyze the original block to see if we are actually splitting an edge
266 // into two edges. This can happen when we have multiple conditional jumps to
267 // the same successor.
268 bool IsEdgeSplit =
269 std::any_of(SplitI.getIterator(), MBB.instr_end(),
270 [&](MachineInstr &MI) {
271 assert(MI.isTerminator() &&((void)0)
272 "Should only have spliced terminators!")((void)0);
273 return llvm::any_of(
274 MI.operands(), [&](MachineOperand &MOp) {
275 return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;
276 });
277 }) ||
278 MBB.getFallThrough() == &UnsplitSucc;
279
280 MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();
281
282 // Insert the new block immediately after the current one. Any existing
283 // fallthrough will be sunk into this new block anyways.
284 MF.insert(std::next(MachineFunction::iterator(&MBB)), &NewMBB);
285
286 // Splice the tail of instructions into the new block.
287 NewMBB.splice(NewMBB.end(), &MBB, SplitI.getIterator(), MBB.end());
288
289 // Copy the necessary succesors (and their probability info) into the new
290 // block.
291 for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
292 if (IsEdgeSplit || *SI != &UnsplitSucc)
293 NewMBB.copySuccessor(&MBB, SI);
294 // Normalize the probabilities if we didn't end up splitting the edge.
295 if (!IsEdgeSplit)
296 NewMBB.normalizeSuccProbs();
297
298 // Now replace all of the moved successors in the original block with the new
299 // block. This will merge their probabilities.
300 for (MachineBasicBlock *Succ : NewMBB.successors())
301 if (Succ != &UnsplitSucc)
302 MBB.replaceSuccessor(Succ, &NewMBB);
303
304 // We should always end up replacing at least one successor.
305 assert(MBB.isSuccessor(&NewMBB) &&((void)0)
306 "Failed to make the new block a successor!")((void)0);
307
308 // Now update all the PHIs.
309 for (MachineBasicBlock *Succ : NewMBB.successors()) {
310 for (MachineInstr &MI : *Succ) {
311 if (!MI.isPHI())
312 break;
313
314 for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;
315 OpIdx += 2) {
316 MachineOperand &OpV = MI.getOperand(OpIdx);
317 MachineOperand &OpMBB = MI.getOperand(OpIdx + 1);
318 assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!")((void)0);
319 if (OpMBB.getMBB() != &MBB)
320 continue;
321
322 // Replace the operand for unsplit successors
323 if (!IsEdgeSplit || Succ != &UnsplitSucc) {
324 OpMBB.setMBB(&NewMBB);
325
326 // We have to continue scanning as there may be multiple entries in
327 // the PHI.
328 continue;
329 }
330
331 // When we have split the edge append a new successor.
332 MI.addOperand(MF, OpV);
333 MI.addOperand(MF, MachineOperand::CreateMBB(&NewMBB));
334 break;
335 }
336 }
337 }
338
339 return NewMBB;
340}
341
342static X86::CondCode getCondFromFCMOV(unsigned Opcode) {
343 switch (Opcode) {
344 default: return X86::COND_INVALID;
345 case X86::CMOVBE_Fp32: case X86::CMOVBE_Fp64: case X86::CMOVBE_Fp80:
346 return X86::COND_BE;
347 case X86::CMOVB_Fp32: case X86::CMOVB_Fp64: case X86::CMOVB_Fp80:
348 return X86::COND_B;
349 case X86::CMOVE_Fp32: case X86::CMOVE_Fp64: case X86::CMOVE_Fp80:
350 return X86::COND_E;
351 case X86::CMOVNBE_Fp32: case X86::CMOVNBE_Fp64: case X86::CMOVNBE_Fp80:
352 return X86::COND_A;
353 case X86::CMOVNB_Fp32: case X86::CMOVNB_Fp64: case X86::CMOVNB_Fp80:
354 return X86::COND_AE;
355 case X86::CMOVNE_Fp32: case X86::CMOVNE_Fp64: case X86::CMOVNE_Fp80:
356 return X86::COND_NE;
357 case X86::CMOVNP_Fp32: case X86::CMOVNP_Fp64: case X86::CMOVNP_Fp80:
358 return X86::COND_NP;
359 case X86::CMOVP_Fp32: case X86::CMOVP_Fp64: case X86::CMOVP_Fp80:
360 return X86::COND_P;
361 }
362}
363
364bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction &MF) {
365 LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()do { } while (false)
1
Loop condition is false. Exiting loop
366 << " **********\n")do { } while (false);
367
368 Subtarget = &MF.getSubtarget<X86Subtarget>();
369 MRI = &MF.getRegInfo();
370 TII = Subtarget->getInstrInfo();
371 TRI = Subtarget->getRegisterInfo();
372 MDT = &getAnalysis<MachineDominatorTree>();
373 PromoteRC = &X86::GR8RegClass;
374
375 if (MF.begin() == MF.end())
2
Taking false branch
376 // Nothing to do for a degenerate empty function...
377 return false;
378
379 // Collect the copies in RPO so that when there are chains where a copy is in
380 // turn copied again we visit the first one first. This ensures we can find
381 // viable locations for testing the original EFLAGS that dominate all the
382 // uses across complex CFGs.
383 SmallVector<MachineInstr *, 4> Copies;
384 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
385 for (MachineBasicBlock *MBB : RPOT)
386 for (MachineInstr &MI : *MBB)
387 if (MI.getOpcode() == TargetOpcode::COPY &&
388 MI.getOperand(0).getReg() == X86::EFLAGS)
389 Copies.push_back(&MI);
390
391 for (MachineInstr *CopyI : Copies) {
3
Assuming '__begin1' is not equal to '__end1'
392 MachineBasicBlock &MBB = *CopyI->getParent();
393
394 MachineOperand &VOp = CopyI->getOperand(1);
395 assert(VOp.isReg() &&((void)0)
396 "The input to the copy for EFLAGS should always be a register!")((void)0);
397 MachineInstr &CopyDefI = *MRI->getVRegDef(VOp.getReg());
398 if (CopyDefI.getOpcode() != TargetOpcode::COPY) {
4
Assuming the condition is false
5
Taking false branch
399 // FIXME: The big likely candidate here are PHI nodes. We could in theory
400 // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
401 // enough that it is probably better to change every other part of LLVM
402 // to avoid creating them. The issue is that once we have PHIs we won't
403 // know which original EFLAGS value we need to capture with our setCCs
404 // below. The end result will be computing a complete set of setCCs that
405 // we *might* want, computing them in every place where we copy *out* of
406 // EFLAGS and then doing SSA formation on all of them to insert necessary
407 // PHI nodes and consume those here. Then hoping that somehow we DCE the
408 // unnecessary ones. This DCE seems very unlikely to be successful and so
409 // we will almost certainly end up with a glut of dead setCC
410 // instructions. Until we have a motivating test case and fail to avoid
411 // it by changing other parts of LLVM's lowering, we refuse to handle
412 // this complex case here.
413 LLVM_DEBUG(do { } while (false)
414 dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";do { } while (false)
415 CopyDefI.dump())do { } while (false);
416 report_fatal_error(
417 "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
418 }
419
420 auto Cleanup = make_scope_exit([&] {
421 // All uses of the EFLAGS copy are now rewritten, kill the copy into
422 // eflags and if dead the copy from.
423 CopyI->eraseFromParent();
424 if (MRI->use_empty(CopyDefI.getOperand(0).getReg()))
425 CopyDefI.eraseFromParent();
426 ++NumCopiesEliminated;
427 });
428
429 MachineOperand &DOp = CopyI->getOperand(0);
430 assert(DOp.isDef() && "Expected register def!")((void)0);
431 assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!")((void)0);
432 if (DOp.isDead())
6
Assuming the condition is false
7
Taking false branch
433 continue;
434
435 MachineBasicBlock *TestMBB = CopyDefI.getParent();
436 auto TestPos = CopyDefI.getIterator();
437 DebugLoc TestLoc = CopyDefI.getDebugLoc();
438
439 LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump())do { } while (false);
8
Loop condition is false. Exiting loop
440
441 // Walk up across live-in EFLAGS to find where they were actually def'ed.
442 //
443 // This copy's def may just be part of a region of blocks covered by
444 // a single def of EFLAGS and we want to find the top of that region where
445 // possible.
446 //
447 // This is essentially a search for a *candidate* reaching definition
448 // location. We don't need to ever find the actual reaching definition here,
449 // but we want to walk up the dominator tree to find the highest point which
450 // would be viable for such a definition.
451 auto HasEFLAGSClobber = [&](MachineBasicBlock::iterator Begin,
452 MachineBasicBlock::iterator End) {
453 // Scan backwards as we expect these to be relatively short and often find
454 // a clobber near the end.
455 return llvm::any_of(
456 llvm::reverse(llvm::make_range(Begin, End)), [&](MachineInstr &MI) {
457 // Flag any instruction (other than the copy we are
458 // currently rewriting) that defs EFLAGS.
459 return &MI != CopyI && MI.findRegisterDefOperand(X86::EFLAGS);
460 });
461 };
462 auto HasEFLAGSClobberPath = [&](MachineBasicBlock *BeginMBB,
463 MachineBasicBlock *EndMBB) {
464 assert(MDT->dominates(BeginMBB, EndMBB) &&((void)0)
465 "Only support paths down the dominator tree!")((void)0);
466 SmallPtrSet<MachineBasicBlock *, 4> Visited;
467 SmallVector<MachineBasicBlock *, 4> Worklist;
468 // We terminate at the beginning. No need to scan it.
469 Visited.insert(BeginMBB);
470 Worklist.push_back(EndMBB);
471 do {
472 auto *MBB = Worklist.pop_back_val();
473 for (auto *PredMBB : MBB->predecessors()) {
474 if (!Visited.insert(PredMBB).second)
475 continue;
476 if (HasEFLAGSClobber(PredMBB->begin(), PredMBB->end()))
477 return true;
478 // Enqueue this block to walk its predecessors.
479 Worklist.push_back(PredMBB);
480 }
481 } while (!Worklist.empty());
482 // No clobber found along a path from the begin to end.
483 return false;
484 };
485 while (TestMBB->isLiveIn(X86::EFLAGS) && !TestMBB->pred_empty() &&
9
Assuming the condition is true
10
Assuming the condition is true
11
Loop condition is true. Entering loop body
486 !HasEFLAGSClobber(TestMBB->begin(), TestPos)) {
487 // Find the nearest common dominator of the predecessors, as
488 // that will be the best candidate to hoist into.
489 MachineBasicBlock *HoistMBB =
490 std::accumulate(std::next(TestMBB->pred_begin()), TestMBB->pred_end(),
12
Calling 'accumulate<std::__wrap_iter<llvm::MachineBasicBlock **>, llvm::MachineBasicBlock *, (lambda at /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp:492:27)>'
491 *TestMBB->pred_begin(),
492 [&](MachineBasicBlock *LHS, MachineBasicBlock *RHS) {
493 return MDT->findNearestCommonDominator(LHS, RHS);
15
Calling 'MachineDominatorTree::findNearestCommonDominator'
494 });
495
496 // Now we need to scan all predecessors that may be reached along paths to
497 // the hoist block. A clobber anywhere in any of these blocks the hoist.
498 // Note that this even handles loops because we require *no* clobbers.
499 if (HasEFLAGSClobberPath(HoistMBB, TestMBB))
500 break;
501
502 // We also need the terminators to not sneakily clobber flags.
503 if (HasEFLAGSClobber(HoistMBB->getFirstTerminator()->getIterator(),
504 HoistMBB->instr_end()))
505 break;
506
507 // We found a viable location, hoist our test position to it.
508 TestMBB = HoistMBB;
509 TestPos = TestMBB->getFirstTerminator()->getIterator();
510 // Clear the debug location as it would just be confusing after hoisting.
511 TestLoc = DebugLoc();
512 }
513 LLVM_DEBUG({do { } while (false)
514 auto DefIt = llvm::find_if(do { } while (false)
515 llvm::reverse(llvm::make_range(TestMBB->instr_begin(), TestPos)),do { } while (false)
516 [&](MachineInstr &MI) {do { } while (false)
517 return MI.findRegisterDefOperand(X86::EFLAGS);do { } while (false)
518 });do { } while (false)
519 if (DefIt.base() != TestMBB->instr_begin()) {do { } while (false)
520 dbgs() << " Using EFLAGS defined by: ";do { } while (false)
521 DefIt->dump();do { } while (false)
522 } else {do { } while (false)
523 dbgs() << " Using live-in flags for BB:\n";do { } while (false)
524 TestMBB->dump();do { } while (false)
525 }do { } while (false)
526 })do { } while (false);
527
528 // While rewriting uses, we buffer jumps and rewrite them in a second pass
529 // because doing so will perturb the CFG that we are walking to find the
530 // uses in the first place.
531 SmallVector<MachineInstr *, 4> JmpIs;
532
533 // Gather the condition flags that have already been preserved in
534 // registers. We do this from scratch each time as we expect there to be
535 // very few of them and we expect to not revisit the same copy definition
536 // many times. If either of those change sufficiently we could build a map
537 // of these up front instead.
538 CondRegArray CondRegs = collectCondsInRegs(*TestMBB, TestPos);
539
540 // Collect the basic blocks we need to scan. Typically this will just be
541 // a single basic block but we may have to scan multiple blocks if the
542 // EFLAGS copy lives into successors.
543 SmallVector<MachineBasicBlock *, 2> Blocks;
544 SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;
545 Blocks.push_back(&MBB);
546
547 do {
548 MachineBasicBlock &UseMBB = *Blocks.pop_back_val();
549
550 // Track when if/when we find a kill of the flags in this block.
551 bool FlagsKilled = false;
552
553 // In most cases, we walk from the beginning to the end of the block. But
554 // when the block is the same block as the copy is from, we will visit it
555 // twice. The first time we start from the copy and go to the end. The
556 // second time we start from the beginning and go to the copy. This lets
557 // us handle copies inside of cycles.
558 // FIXME: This loop is *super* confusing. This is at least in part
559 // a symptom of all of this routine needing to be refactored into
560 // documentable components. Once done, there may be a better way to write
561 // this loop.
562 for (auto MII = (&UseMBB == &MBB && !VisitedBlocks.count(&UseMBB))
563 ? std::next(CopyI->getIterator())
564 : UseMBB.instr_begin(),
565 MIE = UseMBB.instr_end();
566 MII != MIE;) {
567 MachineInstr &MI = *MII++;
568 // If we are in the original copy block and encounter either the copy
569 // def or the copy itself, break so that we don't re-process any part of
570 // the block or process the instructions in the range that was copied
571 // over.
572 if (&MI == CopyI || &MI == &CopyDefI) {
573 assert(&UseMBB == &MBB && VisitedBlocks.count(&MBB) &&((void)0)
574 "Should only encounter these on the second pass over the "((void)0)
575 "original block.")((void)0);
576 break;
577 }
578
579 MachineOperand *FlagUse = MI.findRegisterUseOperand(X86::EFLAGS);
580 if (!FlagUse) {
581 if (MI.findRegisterDefOperand(X86::EFLAGS)) {
582 // If EFLAGS are defined, it's as-if they were killed. We can stop
583 // scanning here.
584 //
585 // NB!!! Many instructions only modify some flags. LLVM currently
586 // models this as clobbering all flags, but if that ever changes
587 // this will need to be carefully updated to handle that more
588 // complex logic.
589 FlagsKilled = true;
590 break;
591 }
592 continue;
593 }
594
595 LLVM_DEBUG(dbgs() << " Rewriting use: "; MI.dump())do { } while (false);
596
597 // Check the kill flag before we rewrite as that may change it.
598 if (FlagUse->isKill())
599 FlagsKilled = true;
600
601 // Once we encounter a branch, the rest of the instructions must also be
602 // branches. We can't rewrite in place here, so we handle them below.
603 //
604 // Note that we don't have to handle tail calls here, even conditional
605 // tail calls, as those are not introduced into the X86 MI until post-RA
606 // branch folding or black placement. As a consequence, we get to deal
607 // with the simpler formulation of conditional branches followed by tail
608 // calls.
609 if (X86::getCondFromBranch(MI) != X86::COND_INVALID) {
610 auto JmpIt = MI.getIterator();
611 do {
612 JmpIs.push_back(&*JmpIt);
613 ++JmpIt;
614 } while (JmpIt != UseMBB.instr_end() &&
615 X86::getCondFromBranch(*JmpIt) !=
616 X86::COND_INVALID);
617 break;
618 }
619
620 // Otherwise we can just rewrite in-place.
621 if (X86::getCondFromCMov(MI) != X86::COND_INVALID) {
622 rewriteCMov(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
623 } else if (getCondFromFCMOV(MI.getOpcode()) != X86::COND_INVALID) {
624 rewriteFCMov(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
625 } else if (X86::getCondFromSETCC(MI) != X86::COND_INVALID) {
626 rewriteSetCC(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
627 } else if (MI.getOpcode() == TargetOpcode::COPY) {
628 rewriteCopy(MI, *FlagUse, CopyDefI);
629 } else {
630 // We assume all other instructions that use flags also def them.
631 assert(MI.findRegisterDefOperand(X86::EFLAGS) &&((void)0)
632 "Expected a def of EFLAGS for this instruction!")((void)0);
633
634 // NB!!! Several arithmetic instructions only *partially* update
635 // flags. Theoretically, we could generate MI code sequences that
636 // would rely on this fact and observe different flags independently.
637 // But currently LLVM models all of these instructions as clobbering
638 // all the flags in an undef way. We rely on that to simplify the
639 // logic.
640 FlagsKilled = true;
641
642 // Generically handle remaining uses as arithmetic instructions.
643 rewriteArithmetic(*TestMBB, TestPos, TestLoc, MI, *FlagUse,
644 CondRegs);
645 }
646
647 // If this was the last use of the flags, we're done.
648 if (FlagsKilled)
649 break;
650 }
651
652 // If the flags were killed, we're done with this block.
653 if (FlagsKilled)
654 continue;
655
656 // Otherwise we need to scan successors for ones where the flags live-in
657 // and queue those up for processing.
658 for (MachineBasicBlock *SuccMBB : UseMBB.successors())
659 if (SuccMBB->isLiveIn(X86::EFLAGS) &&
660 VisitedBlocks.insert(SuccMBB).second) {
661 // We currently don't do any PHI insertion and so we require that the
662 // test basic block dominates all of the use basic blocks. Further, we
663 // can't have a cycle from the test block back to itself as that would
664 // create a cycle requiring a PHI to break it.
665 //
666 // We could in theory do PHI insertion here if it becomes useful by
667 // just taking undef values in along every edge that we don't trace
668 // this EFLAGS copy along. This isn't as bad as fully general PHI
669 // insertion, but still seems like a great deal of complexity.
670 //
671 // Because it is theoretically possible that some earlier MI pass or
672 // other lowering transformation could induce this to happen, we do
673 // a hard check even in non-debug builds here.
674 if (SuccMBB == TestMBB || !MDT->dominates(TestMBB, SuccMBB)) {
675 LLVM_DEBUG({do { } while (false)
676 dbgs()do { } while (false)
677 << "ERROR: Encountered use that is not dominated by our test "do { } while (false)
678 "basic block! Rewriting this would require inserting PHI "do { } while (false)
679 "nodes to track the flag state across the CFG.\n\nTest "do { } while (false)
680 "block:\n";do { } while (false)
681 TestMBB->dump();do { } while (false)
682 dbgs() << "Use block:\n";do { } while (false)
683 SuccMBB->dump();do { } while (false)
684 })do { } while (false);
685 report_fatal_error(
686 "Cannot lower EFLAGS copy when original copy def "
687 "does not dominate all uses.");
688 }
689
690 Blocks.push_back(SuccMBB);
691
692 // After this, EFLAGS will be recreated before each use.
693 SuccMBB->removeLiveIn(X86::EFLAGS);
694 }
695 } while (!Blocks.empty());
696
697 // Now rewrite the jumps that use the flags. These we handle specially
698 // because if there are multiple jumps in a single basic block we'll have
699 // to do surgery on the CFG.
700 MachineBasicBlock *LastJmpMBB = nullptr;
701 for (MachineInstr *JmpI : JmpIs) {
702 // Past the first jump within a basic block we need to split the blocks
703 // apart.
704 if (JmpI->getParent() == LastJmpMBB)
705 splitBlock(*JmpI->getParent(), *JmpI, *TII);
706 else
707 LastJmpMBB = JmpI->getParent();
708
709 rewriteCondJmp(*TestMBB, TestPos, TestLoc, *JmpI, CondRegs);
710 }
711
712 // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
713 // the copy's def operand is itself a kill.
714 }
715
716#ifndef NDEBUG1
717 for (MachineBasicBlock &MBB : MF)
718 for (MachineInstr &MI : MBB)
719 if (MI.getOpcode() == TargetOpcode::COPY &&
720 (MI.getOperand(0).getReg() == X86::EFLAGS ||
721 MI.getOperand(1).getReg() == X86::EFLAGS)) {
722 LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";do { } while (false)
723 MI.dump())do { } while (false);
724 llvm_unreachable("Unlowered EFLAGS copy!")__builtin_unreachable();
725 }
726#endif
727
728 return true;
729}
730
731/// Collect any conditions that have already been set in registers so that we
732/// can re-use them rather than adding duplicates.
733CondRegArray X86FlagsCopyLoweringPass::collectCondsInRegs(
734 MachineBasicBlock &MBB, MachineBasicBlock::iterator TestPos) {
735 CondRegArray CondRegs = {};
736
737 // Scan backwards across the range of instructions with live EFLAGS.
738 for (MachineInstr &MI :
739 llvm::reverse(llvm::make_range(MBB.begin(), TestPos))) {
740 X86::CondCode Cond = X86::getCondFromSETCC(MI);
741 if (Cond != X86::COND_INVALID && !MI.mayStore() &&
742 MI.getOperand(0).isReg() && MI.getOperand(0).getReg().isVirtual()) {
743 assert(MI.getOperand(0).isDef() &&((void)0)
744 "A non-storing SETcc should always define a register!")((void)0);
745 CondRegs[Cond] = MI.getOperand(0).getReg();
746 }
747
748 // Stop scanning when we see the first definition of the EFLAGS as prior to
749 // this we would potentially capture the wrong flag state.
750 if (MI.findRegisterDefOperand(X86::EFLAGS))
751 break;
752 }
753 return CondRegs;
754}
755
756Register X86FlagsCopyLoweringPass::promoteCondToReg(
757 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
758 const DebugLoc &TestLoc, X86::CondCode Cond) {
759 Register Reg = MRI->createVirtualRegister(PromoteRC);
760 auto SetI = BuildMI(TestMBB, TestPos, TestLoc,
761 TII->get(X86::SETCCr), Reg).addImm(Cond);
762 (void)SetI;
763 LLVM_DEBUG(dbgs() << " save cond: "; SetI->dump())do { } while (false);
764 ++NumSetCCsInserted;
765 return Reg;
766}
767
768std::pair<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
769 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
770 const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {
771 unsigned &CondReg = CondRegs[Cond];
772 unsigned &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(Cond)];
773 if (!CondReg && !InvCondReg)
774 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
775
776 if (CondReg)
777 return {CondReg, false};
778 else
779 return {InvCondReg, true};
780}
781
782void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock &MBB,
783 MachineBasicBlock::iterator Pos,
784 const DebugLoc &Loc, unsigned Reg) {
785 auto TestI =
786 BuildMI(MBB, Pos, Loc, TII->get(X86::TEST8rr)).addReg(Reg).addReg(Reg);
787 (void)TestI;
788 LLVM_DEBUG(dbgs() << " test cond: "; TestI->dump())do { } while (false);
789 ++NumTestsInserted;
790}
791
792void X86FlagsCopyLoweringPass::rewriteArithmetic(
793 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
794 const DebugLoc &TestLoc, MachineInstr &MI, MachineOperand &FlagUse,
795 CondRegArray &CondRegs) {
796 // Arithmetic is either reading CF or OF. Figure out which condition we need
797 // to preserve in a register.
798 X86::CondCode Cond = X86::COND_INVALID;
799
800 // The addend to use to reset CF or OF when added to the flag value.
801 int Addend = 0;
802
803 switch (getMnemonicFromOpcode(MI.getOpcode())) {
804 case FlagArithMnemonic::ADC:
805 case FlagArithMnemonic::ADCX:
806 case FlagArithMnemonic::RCL:
807 case FlagArithMnemonic::RCR:
808 case FlagArithMnemonic::SBB:
809 case FlagArithMnemonic::SETB:
810 Cond = X86::COND_B; // CF == 1
811 // Set up an addend that when one is added will need a carry due to not
812 // having a higher bit available.
813 Addend = 255;
814 break;
815
816 case FlagArithMnemonic::ADOX:
817 Cond = X86::COND_O; // OF == 1
818 // Set up an addend that when one is added will turn from positive to
819 // negative and thus overflow in the signed domain.
820 Addend = 127;
821 break;
822 }
823
824 // Now get a register that contains the value of the flag input to the
825 // arithmetic. We require exactly this flag to simplify the arithmetic
826 // required to materialize it back into the flag.
827 unsigned &CondReg = CondRegs[Cond];
828 if (!CondReg)
829 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
830
831 MachineBasicBlock &MBB = *MI.getParent();
832
833 // Insert an instruction that will set the flag back to the desired value.
834 Register TmpReg = MRI->createVirtualRegister(PromoteRC);
835 auto AddI =
836 BuildMI(MBB, MI.getIterator(), MI.getDebugLoc(), TII->get(X86::ADD8ri))
837 .addDef(TmpReg, RegState::Dead)
838 .addReg(CondReg)
839 .addImm(Addend);
840 (void)AddI;
841 LLVM_DEBUG(dbgs() << " add cond: "; AddI->dump())do { } while (false);
842 ++NumAddsInserted;
843 FlagUse.setIsKill(true);
844}
845
846void X86FlagsCopyLoweringPass::rewriteCMov(MachineBasicBlock &TestMBB,
847 MachineBasicBlock::iterator TestPos,
848 const DebugLoc &TestLoc,
849 MachineInstr &CMovI,
850 MachineOperand &FlagUse,
851 CondRegArray &CondRegs) {
852 // First get the register containing this specific condition.
853 X86::CondCode Cond = X86::getCondFromCMov(CMovI);
854 unsigned CondReg;
855 bool Inverted;
856 std::tie(CondReg, Inverted) =
857 getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
858
859 MachineBasicBlock &MBB = *CMovI.getParent();
860
861 // Insert a direct test of the saved register.
862 insertTest(MBB, CMovI.getIterator(), CMovI.getDebugLoc(), CondReg);
863
864 // Rewrite the CMov to use the !ZF flag from the test, and then kill its use
865 // of the flags afterward.
866 CMovI.getOperand(CMovI.getDesc().getNumOperands() - 1)
867 .setImm(Inverted ? X86::COND_E : X86::COND_NE);
868 FlagUse.setIsKill(true);
869 LLVM_DEBUG(dbgs() << " fixed cmov: "; CMovI.dump())do { } while (false);
870}
871
872void X86FlagsCopyLoweringPass::rewriteFCMov(MachineBasicBlock &TestMBB,
873 MachineBasicBlock::iterator TestPos,
874 const DebugLoc &TestLoc,
875 MachineInstr &CMovI,
876 MachineOperand &FlagUse,
877 CondRegArray &CondRegs) {
878 // First get the register containing this specific condition.
879 X86::CondCode Cond = getCondFromFCMOV(CMovI.getOpcode());
880 unsigned CondReg;
881 bool Inverted;
882 std::tie(CondReg, Inverted) =
883 getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
884
885 MachineBasicBlock &MBB = *CMovI.getParent();
886
887 // Insert a direct test of the saved register.
888 insertTest(MBB, CMovI.getIterator(), CMovI.getDebugLoc(), CondReg);
889
890 auto getFCMOVOpcode = [](unsigned Opcode, bool Inverted) {
891 switch (Opcode) {
892 default: llvm_unreachable("Unexpected opcode!")__builtin_unreachable();
893 case X86::CMOVBE_Fp32: case X86::CMOVNBE_Fp32:
894 case X86::CMOVB_Fp32: case X86::CMOVNB_Fp32:
895 case X86::CMOVE_Fp32: case X86::CMOVNE_Fp32:
896 case X86::CMOVP_Fp32: case X86::CMOVNP_Fp32:
897 return Inverted ? X86::CMOVE_Fp32 : X86::CMOVNE_Fp32;
898 case X86::CMOVBE_Fp64: case X86::CMOVNBE_Fp64:
899 case X86::CMOVB_Fp64: case X86::CMOVNB_Fp64:
900 case X86::CMOVE_Fp64: case X86::CMOVNE_Fp64:
901 case X86::CMOVP_Fp64: case X86::CMOVNP_Fp64:
902 return Inverted ? X86::CMOVE_Fp64 : X86::CMOVNE_Fp64;
903 case X86::CMOVBE_Fp80: case X86::CMOVNBE_Fp80:
904 case X86::CMOVB_Fp80: case X86::CMOVNB_Fp80:
905 case X86::CMOVE_Fp80: case X86::CMOVNE_Fp80:
906 case X86::CMOVP_Fp80: case X86::CMOVNP_Fp80:
907 return Inverted ? X86::CMOVE_Fp80 : X86::CMOVNE_Fp80;
908 }
909 };
910
911 // Rewrite the CMov to use the !ZF flag from the test.
912 CMovI.setDesc(TII->get(getFCMOVOpcode(CMovI.getOpcode(), Inverted)));
913 FlagUse.setIsKill(true);
914 LLVM_DEBUG(dbgs() << " fixed fcmov: "; CMovI.dump())do { } while (false);
915}
916
917void X86FlagsCopyLoweringPass::rewriteCondJmp(
918 MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
919 const DebugLoc &TestLoc, MachineInstr &JmpI, CondRegArray &CondRegs) {
920 // First get the register containing this specific condition.
921 X86::CondCode Cond = X86::getCondFromBranch(JmpI);
922 unsigned CondReg;
923 bool Inverted;
924 std::tie(CondReg, Inverted) =
925 getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
926
927 MachineBasicBlock &JmpMBB = *JmpI.getParent();
928
929 // Insert a direct test of the saved register.
930 insertTest(JmpMBB, JmpI.getIterator(), JmpI.getDebugLoc(), CondReg);
931
932 // Rewrite the jump to use the !ZF flag from the test, and kill its use of
933 // flags afterward.
934 JmpI.getOperand(1).setImm(Inverted ? X86::COND_E : X86::COND_NE);
935 JmpI.findRegisterUseOperand(X86::EFLAGS)->setIsKill(true);
936 LLVM_DEBUG(dbgs() << " fixed jCC: "; JmpI.dump())do { } while (false);
937}
938
939void X86FlagsCopyLoweringPass::rewriteCopy(MachineInstr &MI,
940 MachineOperand &FlagUse,
941 MachineInstr &CopyDefI) {
942 // Just replace this copy with the original copy def.
943 MRI->replaceRegWith(MI.getOperand(0).getReg(),
944 CopyDefI.getOperand(0).getReg());
945 MI.eraseFromParent();
946}
947
948void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock &TestMBB,
949 MachineBasicBlock::iterator TestPos,
950 const DebugLoc &TestLoc,
951 MachineInstr &SetCCI,
952 MachineOperand &FlagUse,
953 CondRegArray &CondRegs) {
954 X86::CondCode Cond = X86::getCondFromSETCC(SetCCI);
955 // Note that we can't usefully rewrite this to the inverse without complex
956 // analysis of the users of the setCC. Largely we rely on duplicates which
957 // could have been avoided already being avoided here.
958 unsigned &CondReg = CondRegs[Cond];
959 if (!CondReg)
960 CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
961
962 // Rewriting a register def is trivial: we just replace the register and
963 // remove the setcc.
964 if (!SetCCI.mayStore()) {
965 assert(SetCCI.getOperand(0).isReg() &&((void)0)
966 "Cannot have a non-register defined operand to SETcc!")((void)0);
967 MRI->replaceRegWith(SetCCI.getOperand(0).getReg(), CondReg);
968 SetCCI.eraseFromParent();
969 return;
970 }
971
972 // Otherwise, we need to emit a store.
973 auto MIB = BuildMI(*SetCCI.getParent(), SetCCI.getIterator(),
974 SetCCI.getDebugLoc(), TII->get(X86::MOV8mr));
975 // Copy the address operands.
976 for (int i = 0; i < X86::AddrNumOperands; ++i)
977 MIB.add(SetCCI.getOperand(i));
978
979 MIB.addReg(CondReg);
980
981 MIB.setMemRefs(SetCCI.memoperands());
982
983 SetCCI.eraseFromParent();
984}

/usr/include/c++/v1/numeric

1// -*- C++ -*-
2//===---------------------------- numeric ---------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP_NUMERIC
11#define _LIBCPP_NUMERIC
12
13/*
14 numeric synopsis
15
16namespace std
17{
18
19template <class InputIterator, class T>
20 constexpr T // constexpr since C++20
21 accumulate(InputIterator first, InputIterator last, T init);
22
23template <class InputIterator, class T, class BinaryOperation>
24 constexpr T // constexpr since C++20
25 accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
26
27template<class InputIterator>
28 constexpr typename iterator_traits<InputIterator>::value_type // constexpr since C++20
29 reduce(InputIterator first, InputIterator last); // C++17
30
31template<class InputIterator, class T>
32 constexpr T // constexpr since C++20
33 reduce(InputIterator first, InputIterator last, T init); // C++17
34
35template<class InputIterator, class T, class BinaryOperation>
36 constexpr T // constexpr since C++20
37 reduce(InputIterator first, InputIterator last, T init, BinaryOperation binary_op); // C++17
38
39template <class InputIterator1, class InputIterator2, class T>
40 constexpr T // constexpr since C++20
41 inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init);
42
43template <class InputIterator1, class InputIterator2, class T, class BinaryOperation1, class BinaryOperation2>
44 constexpr T // constexpr since C++20
45 inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
46 T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2);
47
48
49template<class InputIterator1, class InputIterator2, class T>
50 constexpr T // constexpr since C++20
51 transform_reduce(InputIterator1 first1, InputIterator1 last1,
52 InputIterator2 first2, T init); // C++17
53
54template<class InputIterator1, class InputIterator2, class T, class BinaryOperation1, class BinaryOperation2>
55 constexpr T // constexpr since C++20
56 transform_reduce(InputIterator1 first1, InputIterator1 last1,
57 InputIterator2 first2, T init,
58 BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); // C++17
59
60template<class InputIterator, class T, class BinaryOperation, class UnaryOperation>
61 constexpr T // constexpr since C++20
62 transform_reduce(InputIterator first, InputIterator last, T init,
63 BinaryOperation binary_op, UnaryOperation unary_op); // C++17
64
65template <class InputIterator, class OutputIterator>
66 constexpr OutputIterator // constexpr since C++20
67 partial_sum(InputIterator first, InputIterator last, OutputIterator result);
68
69template <class InputIterator, class OutputIterator, class BinaryOperation>
70 constexpr OutputIterator // constexpr since C++20
71 partial_sum(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
72
73template<class InputIterator, class OutputIterator, class T>
74 constexpr OutputIterator // constexpr since C++20
75 exclusive_scan(InputIterator first, InputIterator last,
76 OutputIterator result, T init); // C++17
77
78template<class InputIterator, class OutputIterator, class T, class BinaryOperation>
79 constexpr OutputIterator // constexpr since C++20
80 exclusive_scan(InputIterator first, InputIterator last,
81 OutputIterator result, T init, BinaryOperation binary_op); // C++17
82
83template<class InputIterator, class OutputIterator>
84 constexpr OutputIterator // constexpr since C++20
85 inclusive_scan(InputIterator first, InputIterator last, OutputIterator result); // C++17
86
87template<class InputIterator, class OutputIterator, class BinaryOperation>
88 constexpr OutputIterator // constexpr since C++20
89 inclusive_scan(InputIterator first, InputIterator last,
90 OutputIterator result, BinaryOperation binary_op); // C++17
91
92template<class InputIterator, class OutputIterator, class BinaryOperation, class T>
93 constexpr OutputIterator // constexpr since C++20
94 inclusive_scan(InputIterator first, InputIterator last,
95 OutputIterator result, BinaryOperation binary_op, T init); // C++17
96
97template<class InputIterator, class OutputIterator, class T,
98 class BinaryOperation, class UnaryOperation>
99 constexpr OutputIterator // constexpr since C++20
100 transform_exclusive_scan(InputIterator first, InputIterator last,
101 OutputIterator result, T init,
102 BinaryOperation binary_op, UnaryOperation unary_op); // C++17
103
104template<class InputIterator, class OutputIterator,
105 class BinaryOperation, class UnaryOperation>
106 constexpr OutputIterator // constexpr since C++20
107 transform_inclusive_scan(InputIterator first, InputIterator last,
108 OutputIterator result,
109 BinaryOperation binary_op, UnaryOperation unary_op); // C++17
110
111template<class InputIterator, class OutputIterator,
112 class BinaryOperation, class UnaryOperation, class T>
113 constexpr OutputIterator // constexpr since C++20
114 transform_inclusive_scan(InputIterator first, InputIterator last,
115 OutputIterator result,
116 BinaryOperation binary_op, UnaryOperation unary_op,
117 T init); // C++17
118
119template <class InputIterator, class OutputIterator>
120 constexpr OutputIterator // constexpr since C++20
121 adjacent_difference(InputIterator first, InputIterator last, OutputIterator result);
122
123template <class InputIterator, class OutputIterator, class BinaryOperation>
124 constexpr OutputIterator // constexpr since C++20
125 adjacent_difference(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
126
127template <class ForwardIterator, class T>
128 constexpr void // constexpr since C++20
129 iota(ForwardIterator first, ForwardIterator last, T value);
130
131template <class M, class N>
132 constexpr common_type_t<M,N> gcd(M m, N n); // C++17
133
134template <class M, class N>
135 constexpr common_type_t<M,N> lcm(M m, N n); // C++17
136
137template<class T>
138 constexpr T midpoint(T a, T b) noexcept; // C++20
139
140template<class T>
141 constexpr T* midpoint(T* a, T* b); // C++20
142
143} // std
144
145*/
146
147#include <__config>
148#include <__debug>
149#include <cmath> // for isnormal
150#include <functional>
151#include <iterator>
152#include <limits> // for numeric_limits
153#include <version>
154
155#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
156#pragma GCC system_header
157#endif
158
159_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
160#include <__undef_macros>
161
162_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
163
164template <class _InputIterator, class _Tp>
165_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
166_Tp
167accumulate(_InputIterator __first, _InputIterator __last, _Tp __init)
168{
169 for (; __first != __last; ++__first)
170#if _LIBCPP_STD_VER14 > 17
171 __init = _VSTDstd::__1::move(__init) + *__first;
172#else
173 __init = __init + *__first;
174#endif
175 return __init;
176}
177
178template <class _InputIterator, class _Tp, class _BinaryOperation>
179_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
180_Tp
181accumulate(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOperation __binary_op)
182{
183 for (; __first != __last; ++__first)
13
Loop condition is true. Entering loop body
184#if _LIBCPP_STD_VER14 > 17
185 __init = __binary_op(_VSTDstd::__1::move(__init), *__first);
186#else
187 __init = __binary_op(__init, *__first);
14
Calling 'operator()'
188#endif
189 return __init;
190}
191
192#if _LIBCPP_STD_VER14 > 14
193template <class _InputIterator, class _Tp, class _BinaryOp>
194_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
195_Tp
196reduce(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOp __b)
197{
198 for (; __first != __last; ++__first)
199 __init = __b(__init, *__first);
200 return __init;
201}
202
203template <class _InputIterator, class _Tp>
204_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
205_Tp
206reduce(_InputIterator __first, _InputIterator __last, _Tp __init)
207{
208 return _VSTDstd::__1::reduce(__first, __last, __init, _VSTDstd::__1::plus<>());
209}
210
211template <class _InputIterator>
212_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
213typename iterator_traits<_InputIterator>::value_type
214reduce(_InputIterator __first, _InputIterator __last)
215{
216 return _VSTDstd::__1::reduce(__first, __last,
217 typename iterator_traits<_InputIterator>::value_type{});
218}
219#endif
220
221template <class _InputIterator1, class _InputIterator2, class _Tp>
222_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
223_Tp
224inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init)
225{
226 for (; __first1 != __last1; ++__first1, (void) ++__first2)
227#if _LIBCPP_STD_VER14 > 17
228 __init = _VSTDstd::__1::move(__init) + *__first1 * *__first2;
229#else
230 __init = __init + *__first1 * *__first2;
231#endif
232 return __init;
233}
234
235template <class _InputIterator1, class _InputIterator2, class _Tp, class _BinaryOperation1, class _BinaryOperation2>
236_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
237_Tp
238inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
239 _Tp __init, _BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2)
240{
241 for (; __first1 != __last1; ++__first1, (void) ++__first2)
242#if _LIBCPP_STD_VER14 > 17
243 __init = __binary_op1(_VSTDstd::__1::move(__init), __binary_op2(*__first1, *__first2));
244#else
245 __init = __binary_op1(__init, __binary_op2(*__first1, *__first2));
246#endif
247 return __init;
248}
249
250#if _LIBCPP_STD_VER14 > 14
251template <class _InputIterator, class _Tp, class _BinaryOp, class _UnaryOp>
252_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
253_Tp
254transform_reduce(_InputIterator __first, _InputIterator __last,
255 _Tp __init, _BinaryOp __b, _UnaryOp __u)
256{
257 for (; __first != __last; ++__first)
258 __init = __b(__init, __u(*__first));
259 return __init;
260}
261
262template <class _InputIterator1, class _InputIterator2,
263 class _Tp, class _BinaryOp1, class _BinaryOp2>
264_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
265_Tp
266transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
267 _InputIterator2 __first2, _Tp __init, _BinaryOp1 __b1, _BinaryOp2 __b2)
268{
269 for (; __first1 != __last1; ++__first1, (void) ++__first2)
270 __init = __b1(__init, __b2(*__first1, *__first2));
271 return __init;
272}
273
274template <class _InputIterator1, class _InputIterator2, class _Tp>
275_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
276_Tp
277transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
278 _InputIterator2 __first2, _Tp __init)
279{
280 return _VSTDstd::__1::transform_reduce(__first1, __last1, __first2, _VSTDstd::__1::move(__init),
281 _VSTDstd::__1::plus<>(), _VSTDstd::__1::multiplies<>());
282}
283#endif
284
285template <class _InputIterator, class _OutputIterator>
286_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
287_OutputIterator
288partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
289{
290 if (__first != __last)
291 {
292 typename iterator_traits<_InputIterator>::value_type __t(*__first);
293 *__result = __t;
294 for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
295 {
296#if _LIBCPP_STD_VER14 > 17
297 __t = _VSTDstd::__1::move(__t) + *__first;
298#else
299 __t = __t + *__first;
300#endif
301 *__result = __t;
302 }
303 }
304 return __result;
305}
306
307template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
308_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
309_OutputIterator
310partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
311 _BinaryOperation __binary_op)
312{
313 if (__first != __last)
314 {
315 typename iterator_traits<_InputIterator>::value_type __t(*__first);
316 *__result = __t;
317 for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
318 {
319#if _LIBCPP_STD_VER14 > 17
320 __t = __binary_op(_VSTDstd::__1::move(__t), *__first);
321#else
322 __t = __binary_op(__t, *__first);
323#endif
324 *__result = __t;
325 }
326 }
327 return __result;
328}
329
330#if _LIBCPP_STD_VER14 > 14
331template <class _InputIterator, class _OutputIterator, class _Tp, class _BinaryOp>
332_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
333_OutputIterator
334exclusive_scan(_InputIterator __first, _InputIterator __last,
335 _OutputIterator __result, _Tp __init, _BinaryOp __b)
336{
337 if (__first != __last)
338 {
339 _Tp __tmp(__b(__init, *__first));
340 while (true)
341 {
342 *__result = _VSTDstd::__1::move(__init);
343 ++__result;
344 ++__first;
345 if (__first == __last)
346 break;
347 __init = _VSTDstd::__1::move(__tmp);
348 __tmp = __b(__init, *__first);
349 }
350 }
351 return __result;
352}
353
354template <class _InputIterator, class _OutputIterator, class _Tp>
355_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
356_OutputIterator
357exclusive_scan(_InputIterator __first, _InputIterator __last,
358 _OutputIterator __result, _Tp __init)
359{
360 return _VSTDstd::__1::exclusive_scan(__first, __last, __result, __init, _VSTDstd::__1::plus<>());
361}
362
363template <class _InputIterator, class _OutputIterator, class _Tp, class _BinaryOp>
364_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
365_OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last,
366 _OutputIterator __result, _BinaryOp __b, _Tp __init)
367{
368 for (; __first != __last; ++__first, (void) ++__result) {
369 __init = __b(__init, *__first);
370 *__result = __init;
371 }
372 return __result;
373}
374
375template <class _InputIterator, class _OutputIterator, class _BinaryOp>
376_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
377_OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last,
378 _OutputIterator __result, _BinaryOp __b)
379{
380 if (__first != __last) {
381 typename iterator_traits<_InputIterator>::value_type __init = *__first;
382 *__result++ = __init;
383 if (++__first != __last)
384 return _VSTDstd::__1::inclusive_scan(__first, __last, __result, __b, __init);
385 }
386
387 return __result;
388}
389
390template <class _InputIterator, class _OutputIterator>
391_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
392_OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last,
393 _OutputIterator __result)
394{
395 return _VSTDstd::__1::inclusive_scan(__first, __last, __result, _VSTDstd::__1::plus<>());
396}
397
398template <class _InputIterator, class _OutputIterator, class _Tp,
399 class _BinaryOp, class _UnaryOp>
400_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
401_OutputIterator
402transform_exclusive_scan(_InputIterator __first, _InputIterator __last,
403 _OutputIterator __result, _Tp __init,
404 _BinaryOp __b, _UnaryOp __u)
405{
406 if (__first != __last)
407 {
408 _Tp __saved = __init;
409 do
410 {
411 __init = __b(__init, __u(*__first));
412 *__result = __saved;
413 __saved = __init;
414 ++__result;
415 } while (++__first != __last);
416 }
417 return __result;
418}
419
420template <class _InputIterator, class _OutputIterator, class _Tp, class _BinaryOp, class _UnaryOp>
421_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
422_OutputIterator
423transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
424 _OutputIterator __result, _BinaryOp __b, _UnaryOp __u, _Tp __init)
425{
426 for (; __first != __last; ++__first, (void) ++__result) {
427 __init = __b(__init, __u(*__first));
428 *__result = __init;
429 }
430
431 return __result;
432}
433
434template <class _InputIterator, class _OutputIterator, class _BinaryOp, class _UnaryOp>
435_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
436_OutputIterator
437transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
438 _OutputIterator __result, _BinaryOp __b, _UnaryOp __u)
439{
440 if (__first != __last) {
441 typename iterator_traits<_InputIterator>::value_type __init = __u(*__first);
442 *__result++ = __init;
443 if (++__first != __last)
444 return _VSTDstd::__1::transform_inclusive_scan(__first, __last, __result, __b, __u, __init);
445 }
446
447 return __result;
448}
449#endif
450
451template <class _InputIterator, class _OutputIterator>
452_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
453_OutputIterator
454adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
455{
456 if (__first != __last)
457 {
458 typename iterator_traits<_InputIterator>::value_type __acc(*__first);
459 *__result = __acc;
460 for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
461 {
462 typename iterator_traits<_InputIterator>::value_type __val(*__first);
463#if _LIBCPP_STD_VER14 > 17
464 *__result = __val - _VSTDstd::__1::move(__acc);
465#else
466 *__result = __val - __acc;
467#endif
468 __acc = _VSTDstd::__1::move(__val);
469 }
470 }
471 return __result;
472}
473
474template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
475_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
476_OutputIterator
477adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
478 _BinaryOperation __binary_op)
479{
480 if (__first != __last)
481 {
482 typename iterator_traits<_InputIterator>::value_type __acc(*__first);
483 *__result = __acc;
484 for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
485 {
486 typename iterator_traits<_InputIterator>::value_type __val(*__first);
487#if _LIBCPP_STD_VER14 > 17
488 *__result = __binary_op(__val, _VSTDstd::__1::move(__acc));
489#else
490 *__result = __binary_op(__val, __acc);
491#endif
492 __acc = _VSTDstd::__1::move(__val);
493 }
494 }
495 return __result;
496}
497
498template <class _ForwardIterator, class _Tp>
499_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
500void
501iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value_)
502{
503 for (; __first != __last; ++__first, (void) ++__value_)
504 *__first = __value_;
505}
506
507
508#if _LIBCPP_STD_VER14 > 14
509template <typename _Result, typename _Source, bool _IsSigned = is_signed<_Source>::value> struct __ct_abs;
510
511template <typename _Result, typename _Source>
512struct __ct_abs<_Result, _Source, true> {
513 _LIBCPP_CONSTEXPRconstexpr _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
514 _Result operator()(_Source __t) const noexcept
515 {
516 if (__t >= 0) return __t;
517 if (__t == numeric_limits<_Source>::min()) return -static_cast<_Result>(__t);
518 return -__t;
519 }
520};
521
522template <typename _Result, typename _Source>
523struct __ct_abs<_Result, _Source, false> {
524 _LIBCPP_CONSTEXPRconstexpr _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
525 _Result operator()(_Source __t) const noexcept { return __t; }
526};
527
528
529template<class _Tp>
530_LIBCPP_CONSTEXPRconstexpr _LIBCPP_HIDDEN__attribute__ ((__visibility__("hidden")))
531_Tp __gcd(_Tp __m, _Tp __n)
532{
533 static_assert((!is_signed<_Tp>::value), "");
534 return __n == 0 ? __m : _VSTDstd::__1::__gcd<_Tp>(__n, __m % __n);
535}
536
537
538template<class _Tp, class _Up>
539_LIBCPP_CONSTEXPRconstexpr _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
540common_type_t<_Tp,_Up>
541gcd(_Tp __m, _Up __n)
542{
543 static_assert((is_integral<_Tp>::value && is_integral<_Up>::value), "Arguments to gcd must be integer types");
544 static_assert((!is_same<typename remove_cv<_Tp>::type, bool>::value), "First argument to gcd cannot be bool" );
545 static_assert((!is_same<typename remove_cv<_Up>::type, bool>::value), "Second argument to gcd cannot be bool" );
546 using _Rp = common_type_t<_Tp,_Up>;
547 using _Wp = make_unsigned_t<_Rp>;
548 return static_cast<_Rp>(_VSTDstd::__1::__gcd(
549 static_cast<_Wp>(__ct_abs<_Rp, _Tp>()(__m)),
550 static_cast<_Wp>(__ct_abs<_Rp, _Up>()(__n))));
551}
552
553template<class _Tp, class _Up>
554_LIBCPP_CONSTEXPRconstexpr _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
555common_type_t<_Tp,_Up>
556lcm(_Tp __m, _Up __n)
557{
558 static_assert((is_integral<_Tp>::value && is_integral<_Up>::value), "Arguments to lcm must be integer types");
559 static_assert((!is_same<typename remove_cv<_Tp>::type, bool>::value), "First argument to lcm cannot be bool" );
560 static_assert((!is_same<typename remove_cv<_Up>::type, bool>::value), "Second argument to lcm cannot be bool" );
561 if (__m == 0 || __n == 0)
562 return 0;
563
564 using _Rp = common_type_t<_Tp,_Up>;
565 _Rp __val1 = __ct_abs<_Rp, _Tp>()(__m) / _VSTDstd::__1::gcd(__m, __n);
566 _Rp __val2 = __ct_abs<_Rp, _Up>()(__n);
567 _LIBCPP_ASSERT((numeric_limits<_Rp>::max() / __val1 > __val2), "Overflow in lcm")((void)0);
568 return __val1 * __val2;
569}
570
571#endif /* _LIBCPP_STD_VER > 14 */
572
573#if _LIBCPP_STD_VER14 > 17
574template <class _Tp>
575_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr
576enable_if_t<is_integral_v<_Tp> && !is_same_v<bool, _Tp> && !is_null_pointer_v<_Tp>, _Tp>
577midpoint(_Tp __a, _Tp __b) noexcept
578_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK__attribute__((__no_sanitize__("unsigned-integer-overflow")))
579{
580 using _Up = make_unsigned_t<_Tp>;
581 constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
582
583 _Up __diff = _Up(__b) - _Up(__a);
584 _Up __sign_bit = __b < __a;
585
586 _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
587
588 return __a + __half_diff;
589}
590
591
592template <class _TPtr>
593_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr
594enable_if_t<is_pointer_v<_TPtr>
595 && is_object_v<remove_pointer_t<_TPtr>>
596 && ! is_void_v<remove_pointer_t<_TPtr>>
597 && (sizeof(remove_pointer_t<_TPtr>) > 0), _TPtr>
598midpoint(_TPtr __a, _TPtr __b) noexcept
599{
600 return __a + _VSTDstd::__1::midpoint(ptrdiff_t(0), __b - __a);
601}
602
603
604template <typename _Tp>
605constexpr int __sign(_Tp __val) {
606 return (_Tp(0) < __val) - (__val < _Tp(0));
607}
608
609template <typename _Fp>
610constexpr _Fp __fp_abs(_Fp __f) { return __f >= 0 ? __f : -__f; }
611
612template <class _Fp>
613_LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr
614enable_if_t<is_floating_point_v<_Fp>, _Fp>
615midpoint(_Fp __a, _Fp __b) noexcept
616{
617 constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
618 constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
619 return __fp_abs(__a) <= __hi && __fp_abs(__b) <= __hi ? // typical case: overflow is impossible
620 (__a + __b)/2 : // always correctly rounded
621 __fp_abs(__a) < __lo ? __a + __b/2 : // not safe to halve a
622 __fp_abs(__b) < __lo ? __a/2 + __b : // not safe to halve b
623 __a/2 + __b/2; // otherwise correctly rounded
624}
625
626#endif // _LIBCPP_STD_VER > 17
627
628_LIBCPP_END_NAMESPACE_STD} }
629
630_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
631
632#if defined(_LIBCPP_HAS_PARALLEL_ALGORITHMS) && _LIBCPP_STD_VER14 >= 17
633# include <__pstl_numeric>
634#endif
635
636#endif // _LIBCPP_NUMERIC

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/CodeGen/MachineDominators.h

1//==- llvm/CodeGen/MachineDominators.h - Machine Dom Calculation -*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines classes mirroring those in llvm/Analysis/Dominators.h,
10// but for target-specific code rather than target-independent IR.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_MACHINEDOMINATORS_H
15#define LLVM_CODEGEN_MACHINEDOMINATORS_H
16
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/Support/GenericDomTree.h"
23#include "llvm/Support/GenericDomTreeConstruction.h"
24#include <cassert>
25#include <memory>
26
27namespace llvm {
28
29template <>
30inline void DominatorTreeBase<MachineBasicBlock, false>::addRoot(
31 MachineBasicBlock *MBB) {
32 this->Roots.push_back(MBB);
33}
34
35extern template class DomTreeNodeBase<MachineBasicBlock>;
36extern template class DominatorTreeBase<MachineBasicBlock, false>; // DomTree
37extern template class DominatorTreeBase<MachineBasicBlock, true>; // PostDomTree
38
39using MachineDomTreeNode = DomTreeNodeBase<MachineBasicBlock>;
40
41//===-------------------------------------
42/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
43/// compute a normal dominator tree.
44///
45class MachineDominatorTree : public MachineFunctionPass {
46 using DomTreeT = DomTreeBase<MachineBasicBlock>;
47
48 /// Helper structure used to hold all the basic blocks
49 /// involved in the split of a critical edge.
50 struct CriticalEdge {
51 MachineBasicBlock *FromBB;
52 MachineBasicBlock *ToBB;
53 MachineBasicBlock *NewBB;
54 };
55
56 /// Pile up all the critical edges to be split.
57 /// The splitting of a critical edge is local and thus, it is possible
58 /// to apply several of those changes at the same time.
59 mutable SmallVector<CriticalEdge, 32> CriticalEdgesToSplit;
60
61 /// Remember all the basic blocks that are inserted during
62 /// edge splitting.
63 /// Invariant: NewBBs == all the basic blocks contained in the NewBB
64 /// field of all the elements of CriticalEdgesToSplit.
65 /// I.e., forall elt in CriticalEdgesToSplit, it exists BB in NewBBs
66 /// such as BB == elt.NewBB.
67 mutable SmallSet<MachineBasicBlock *, 32> NewBBs;
68
69 /// The DominatorTreeBase that is used to compute a normal dominator tree.
70 std::unique_ptr<DomTreeT> DT;
71
72 /// Apply all the recorded critical edges to the DT.
73 /// This updates the underlying DT information in a way that uses
74 /// the fast query path of DT as much as possible.
75 ///
76 /// \post CriticalEdgesToSplit.empty().
77 void applySplitCriticalEdges() const;
78
79public:
80 static char ID; // Pass ID, replacement for typeid
81
82 MachineDominatorTree();
83 explicit MachineDominatorTree(MachineFunction &MF) : MachineFunctionPass(ID) {
84 calculate(MF);
85 }
86
87 DomTreeT &getBase() {
88 if (!DT) DT.reset(new DomTreeT());
89 applySplitCriticalEdges();
90 return *DT;
91 }
92
93 void getAnalysisUsage(AnalysisUsage &AU) const override;
94
95 MachineBasicBlock *getRoot() const {
96 applySplitCriticalEdges();
97 return DT->getRoot();
98 }
99
100 MachineDomTreeNode *getRootNode() const {
101 applySplitCriticalEdges();
102 return DT->getRootNode();
103 }
104
105 bool runOnMachineFunction(MachineFunction &F) override;
106
107 void calculate(MachineFunction &F);
108
109 bool dominates(const MachineDomTreeNode *A,
110 const MachineDomTreeNode *B) const {
111 applySplitCriticalEdges();
112 return DT->dominates(A, B);
113 }
114
115 bool dominates(const MachineBasicBlock *A, const MachineBasicBlock *B) const {
116 applySplitCriticalEdges();
117 return DT->dominates(A, B);
118 }
119
120 // dominates - Return true if A dominates B. This performs the
121 // special checks necessary if A and B are in the same basic block.
122 bool dominates(const MachineInstr *A, const MachineInstr *B) const {
123 applySplitCriticalEdges();
124 const MachineBasicBlock *BBA = A->getParent(), *BBB = B->getParent();
125 if (BBA != BBB) return DT->dominates(BBA, BBB);
126
127 // Loop through the basic block until we find A or B.
128 MachineBasicBlock::const_iterator I = BBA->begin();
129 for (; &*I != A && &*I != B; ++I)
130 /*empty*/ ;
131
132 return &*I == A;
133 }
134
135 bool properlyDominates(const MachineDomTreeNode *A,
136 const MachineDomTreeNode *B) const {
137 applySplitCriticalEdges();
138 return DT->properlyDominates(A, B);
139 }
140
141 bool properlyDominates(const MachineBasicBlock *A,
142 const MachineBasicBlock *B) const {
143 applySplitCriticalEdges();
144 return DT->properlyDominates(A, B);
145 }
146
147 /// findNearestCommonDominator - Find nearest common dominator basic block
148 /// for basic block A and B. If there is no such block then return NULL.
149 MachineBasicBlock *findNearestCommonDominator(MachineBasicBlock *A,
150 MachineBasicBlock *B) {
151 applySplitCriticalEdges();
152 return DT->findNearestCommonDominator(A, B);
16
Calling 'DominatorTreeBase::findNearestCommonDominator'
153 }
154
155 MachineDomTreeNode *operator[](MachineBasicBlock *BB) const {
156 applySplitCriticalEdges();
157 return DT->getNode(BB);
158 }
159
160 /// getNode - return the (Post)DominatorTree node for the specified basic
161 /// block. This is the same as using operator[] on this class.
162 ///
163 MachineDomTreeNode *getNode(MachineBasicBlock *BB) const {
164 applySplitCriticalEdges();
165 return DT->getNode(BB);
166 }
167
168 /// addNewBlock - Add a new node to the dominator tree information. This
169 /// creates a new node as a child of DomBB dominator node,linking it into
170 /// the children list of the immediate dominator.
171 MachineDomTreeNode *addNewBlock(MachineBasicBlock *BB,
172 MachineBasicBlock *DomBB) {
173 applySplitCriticalEdges();
174 return DT->addNewBlock(BB, DomBB);
175 }
176
177 /// changeImmediateDominator - This method is used to update the dominator
178 /// tree information when a node's immediate dominator changes.
179 ///
180 void changeImmediateDominator(MachineBasicBlock *N,
181 MachineBasicBlock *NewIDom) {
182 applySplitCriticalEdges();
183 DT->changeImmediateDominator(N, NewIDom);
184 }
185
186 void changeImmediateDominator(MachineDomTreeNode *N,
187 MachineDomTreeNode *NewIDom) {
188 applySplitCriticalEdges();
189 DT->changeImmediateDominator(N, NewIDom);
190 }
191
192 /// eraseNode - Removes a node from the dominator tree. Block must not
193 /// dominate any other blocks. Removes node from its immediate dominator's
194 /// children list. Deletes dominator node associated with basic block BB.
195 void eraseNode(MachineBasicBlock *BB) {
196 applySplitCriticalEdges();
197 DT->eraseNode(BB);
198 }
199
200 /// splitBlock - BB is split and now it has one successor. Update dominator
201 /// tree to reflect this change.
202 void splitBlock(MachineBasicBlock* NewBB) {
203 applySplitCriticalEdges();
204 DT->splitBlock(NewBB);
205 }
206
207 /// isReachableFromEntry - Return true if A is dominated by the entry
208 /// block of the function containing it.
209 bool isReachableFromEntry(const MachineBasicBlock *A) {
210 applySplitCriticalEdges();
211 return DT->isReachableFromEntry(A);
212 }
213
214 void releaseMemory() override;
215
216 void verifyAnalysis() const override;
217
218 void print(raw_ostream &OS, const Module*) const override;
219
220 /// Record that the critical edge (FromBB, ToBB) has been
221 /// split with NewBB.
222 /// This is best to use this method instead of directly update the
223 /// underlying information, because this helps mitigating the
224 /// number of time the DT information is invalidated.
225 ///
226 /// \note Do not use this method with regular edges.
227 ///
228 /// \note To benefit from the compile time improvement incurred by this
229 /// method, the users of this method have to limit the queries to the DT
230 /// interface between two edges splitting. In other words, they have to
231 /// pack the splitting of critical edges as much as possible.
232 void recordSplitCriticalEdge(MachineBasicBlock *FromBB,
233 MachineBasicBlock *ToBB,
234 MachineBasicBlock *NewBB) {
235 bool Inserted = NewBBs.insert(NewBB).second;
236 (void)Inserted;
237 assert(Inserted &&((void)0)
238 "A basic block inserted via edge splitting cannot appear twice")((void)0);
239 CriticalEdgesToSplit.push_back({FromBB, ToBB, NewBB});
240 }
241};
242
243//===-------------------------------------
244/// DominatorTree GraphTraits specialization so the DominatorTree can be
245/// iterable by generic graph iterators.
246///
247
248template <class Node, class ChildIterator>
249struct MachineDomTreeGraphTraitsBase {
250 using NodeRef = Node *;
251 using ChildIteratorType = ChildIterator;
252
253 static NodeRef getEntryNode(NodeRef N) { return N; }
254 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
255 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
256};
257
258template <class T> struct GraphTraits;
259
260template <>
261struct GraphTraits<MachineDomTreeNode *>
262 : public MachineDomTreeGraphTraitsBase<MachineDomTreeNode,
263 MachineDomTreeNode::const_iterator> {
264};
265
266template <>
267struct GraphTraits<const MachineDomTreeNode *>
268 : public MachineDomTreeGraphTraitsBase<const MachineDomTreeNode,
269 MachineDomTreeNode::const_iterator> {
270};
271
272template <> struct GraphTraits<MachineDominatorTree*>
273 : public GraphTraits<MachineDomTreeNode *> {
274 static NodeRef getEntryNode(MachineDominatorTree *DT) {
275 return DT->getRootNode();
276 }
277};
278
279} // end namespace llvm
280
281#endif // LLVM_CODEGEN_MACHINEDOMINATORS_H

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/GenericDomTree.h

1//===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This file defines a set of templates that efficiently compute a dominator
11/// tree over a generic graph. This is used typically in LLVM for fast
12/// dominance queries on the CFG, but is fully generic w.r.t. the underlying
13/// graph types.
14///
15/// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
16/// on the graph's NodeRef. The NodeRef should be a pointer and,
17/// NodeRef->getParent() must return the parent node that is also a pointer.
18///
19/// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_SUPPORT_GENERICDOMTREE_H
24#define LLVM_SUPPORT_GENERICDOMTREE_H
25
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/GraphTraits.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/Support/CFGDiff.h"
32#include "llvm/Support/CFGUpdate.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <iterator>
38#include <memory>
39#include <type_traits>
40#include <utility>
41
42namespace llvm {
43
44template <typename NodeT, bool IsPostDom>
45class DominatorTreeBase;
46
47namespace DomTreeBuilder {
48template <typename DomTreeT>
49struct SemiNCAInfo;
50} // namespace DomTreeBuilder
51
52/// Base class for the actual dominator tree node.
53template <class NodeT> class DomTreeNodeBase {
54 friend class PostDominatorTree;
55 friend class DominatorTreeBase<NodeT, false>;
56 friend class DominatorTreeBase<NodeT, true>;
57 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, false>>;
58 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, true>>;
59
60 NodeT *TheBB;
61 DomTreeNodeBase *IDom;
62 unsigned Level;
63 SmallVector<DomTreeNodeBase *, 4> Children;
64 mutable unsigned DFSNumIn = ~0;
65 mutable unsigned DFSNumOut = ~0;
66
67 public:
68 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
69 : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
70
71 using iterator = typename SmallVector<DomTreeNodeBase *, 4>::iterator;
72 using const_iterator =
73 typename SmallVector<DomTreeNodeBase *, 4>::const_iterator;
74
75 iterator begin() { return Children.begin(); }
76 iterator end() { return Children.end(); }
77 const_iterator begin() const { return Children.begin(); }
78 const_iterator end() const { return Children.end(); }
79
80 DomTreeNodeBase *const &back() const { return Children.back(); }
81 DomTreeNodeBase *&back() { return Children.back(); }
82
83 iterator_range<iterator> children() { return make_range(begin(), end()); }
84 iterator_range<const_iterator> children() const {
85 return make_range(begin(), end());
86 }
87
88 NodeT *getBlock() const { return TheBB; }
89 DomTreeNodeBase *getIDom() const { return IDom; }
90 unsigned getLevel() const { return Level; }
91
92 std::unique_ptr<DomTreeNodeBase> addChild(
93 std::unique_ptr<DomTreeNodeBase> C) {
94 Children.push_back(C.get());
95 return C;
96 }
97
98 bool isLeaf() const { return Children.empty(); }
99 size_t getNumChildren() const { return Children.size(); }
100
101 void clearAllChildren() { Children.clear(); }
102
103 bool compare(const DomTreeNodeBase *Other) const {
104 if (getNumChildren() != Other->getNumChildren())
105 return true;
106
107 if (Level != Other->Level) return true;
108
109 SmallPtrSet<const NodeT *, 4> OtherChildren;
110 for (const DomTreeNodeBase *I : *Other) {
111 const NodeT *Nd = I->getBlock();
112 OtherChildren.insert(Nd);
113 }
114
115 for (const DomTreeNodeBase *I : *this) {
116 const NodeT *N = I->getBlock();
117 if (OtherChildren.count(N) == 0)
118 return true;
119 }
120 return false;
121 }
122
123 void setIDom(DomTreeNodeBase *NewIDom) {
124 assert(IDom && "No immediate dominator?")((void)0);
125 if (IDom == NewIDom) return;
126
127 auto I = find(IDom->Children, this);
128 assert(I != IDom->Children.end() &&((void)0)
129 "Not in immediate dominator children set!")((void)0);
130 // I am no longer your child...
131 IDom->Children.erase(I);
132
133 // Switch to new dominator
134 IDom = NewIDom;
135 IDom->Children.push_back(this);
136
137 UpdateLevel();
138 }
139
140 /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
141 /// in the dominator tree. They are only guaranteed valid if
142 /// updateDFSNumbers() has been called.
143 unsigned getDFSNumIn() const { return DFSNumIn; }
144 unsigned getDFSNumOut() const { return DFSNumOut; }
145
146private:
147 // Return true if this node is dominated by other. Use this only if DFS info
148 // is valid.
149 bool DominatedBy(const DomTreeNodeBase *other) const {
150 return this->DFSNumIn >= other->DFSNumIn &&
151 this->DFSNumOut <= other->DFSNumOut;
152 }
153
154 void UpdateLevel() {
155 assert(IDom)((void)0);
156 if (Level == IDom->Level + 1) return;
157
158 SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
159
160 while (!WorkStack.empty()) {
161 DomTreeNodeBase *Current = WorkStack.pop_back_val();
162 Current->Level = Current->IDom->Level + 1;
163
164 for (DomTreeNodeBase *C : *Current) {
165 assert(C->IDom)((void)0);
166 if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
167 }
168 }
169 }
170};
171
172template <class NodeT>
173raw_ostream &operator<<(raw_ostream &O, const DomTreeNodeBase<NodeT> *Node) {
174 if (Node->getBlock())
175 Node->getBlock()->printAsOperand(O, false);
176 else
177 O << " <<exit node>>";
178
179 O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
180 << Node->getLevel() << "]\n";
181
182 return O;
183}
184
185template <class NodeT>
186void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &O,
187 unsigned Lev) {
188 O.indent(2 * Lev) << "[" << Lev << "] " << N;
189 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
190 E = N->end();
191 I != E; ++I)
192 PrintDomTree<NodeT>(*I, O, Lev + 1);
193}
194
195namespace DomTreeBuilder {
196// The routines below are provided in a separate header but referenced here.
197template <typename DomTreeT>
198void Calculate(DomTreeT &DT);
199
200template <typename DomTreeT>
201void CalculateWithUpdates(DomTreeT &DT,
202 ArrayRef<typename DomTreeT::UpdateType> Updates);
203
204template <typename DomTreeT>
205void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
206 typename DomTreeT::NodePtr To);
207
208template <typename DomTreeT>
209void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
210 typename DomTreeT::NodePtr To);
211
212template <typename DomTreeT>
213void ApplyUpdates(DomTreeT &DT,
214 GraphDiff<typename DomTreeT::NodePtr,
215 DomTreeT::IsPostDominator> &PreViewCFG,
216 GraphDiff<typename DomTreeT::NodePtr,
217 DomTreeT::IsPostDominator> *PostViewCFG);
218
219template <typename DomTreeT>
220bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
221} // namespace DomTreeBuilder
222
223/// Core dominator tree base class.
224///
225/// This class is a generic template over graph nodes. It is instantiated for
226/// various graphs in the LLVM IR or in the code generator.
227template <typename NodeT, bool IsPostDom>
228class DominatorTreeBase {
229 public:
230 static_assert(std::is_pointer<typename GraphTraits<NodeT *>::NodeRef>::value,
231 "Currently DominatorTreeBase supports only pointer nodes");
232 using NodeType = NodeT;
233 using NodePtr = NodeT *;
234 using ParentPtr = decltype(std::declval<NodeT *>()->getParent());
235 static_assert(std::is_pointer<ParentPtr>::value,
236 "Currently NodeT's parent must be a pointer type");
237 using ParentType = std::remove_pointer_t<ParentPtr>;
238 static constexpr bool IsPostDominator = IsPostDom;
239
240 using UpdateType = cfg::Update<NodePtr>;
241 using UpdateKind = cfg::UpdateKind;
242 static constexpr UpdateKind Insert = UpdateKind::Insert;
243 static constexpr UpdateKind Delete = UpdateKind::Delete;
244
245 enum class VerificationLevel { Fast, Basic, Full };
246
247protected:
248 // Dominators always have a single root, postdominators can have more.
249 SmallVector<NodeT *, IsPostDom ? 4 : 1> Roots;
250
251 using DomTreeNodeMapType =
252 DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>;
253 DomTreeNodeMapType DomTreeNodes;
254 DomTreeNodeBase<NodeT> *RootNode = nullptr;
255 ParentPtr Parent = nullptr;
256
257 mutable bool DFSInfoValid = false;
258 mutable unsigned int SlowQueries = 0;
259
260 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase>;
261
262 public:
263 DominatorTreeBase() {}
264
265 DominatorTreeBase(DominatorTreeBase &&Arg)
266 : Roots(std::move(Arg.Roots)),
267 DomTreeNodes(std::move(Arg.DomTreeNodes)),
268 RootNode(Arg.RootNode),
269 Parent(Arg.Parent),
270 DFSInfoValid(Arg.DFSInfoValid),
271 SlowQueries(Arg.SlowQueries) {
272 Arg.wipe();
273 }
274
275 DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
276 Roots = std::move(RHS.Roots);
277 DomTreeNodes = std::move(RHS.DomTreeNodes);
278 RootNode = RHS.RootNode;
279 Parent = RHS.Parent;
280 DFSInfoValid = RHS.DFSInfoValid;
281 SlowQueries = RHS.SlowQueries;
282 RHS.wipe();
283 return *this;
284 }
285
286 DominatorTreeBase(const DominatorTreeBase &) = delete;
287 DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
288
289 /// Iteration over roots.
290 ///
291 /// This may include multiple blocks if we are computing post dominators.
292 /// For forward dominators, this will always be a single block (the entry
293 /// block).
294 using root_iterator = typename SmallVectorImpl<NodeT *>::iterator;
295 using const_root_iterator = typename SmallVectorImpl<NodeT *>::const_iterator;
296
297 root_iterator root_begin() { return Roots.begin(); }
298 const_root_iterator root_begin() const { return Roots.begin(); }
299 root_iterator root_end() { return Roots.end(); }
300 const_root_iterator root_end() const { return Roots.end(); }
301
302 size_t root_size() const { return Roots.size(); }
303
304 iterator_range<root_iterator> roots() {
305 return make_range(root_begin(), root_end());
306 }
307 iterator_range<const_root_iterator> roots() const {
308 return make_range(root_begin(), root_end());
309 }
310
311 /// isPostDominator - Returns true if analysis based of postdoms
312 ///
313 bool isPostDominator() const { return IsPostDominator; }
18
Returning zero (loaded from 'IsPostDominator'), which participates in a condition later
314
315 /// compare - Return false if the other dominator tree base matches this
316 /// dominator tree base. Otherwise return true.
317 bool compare(const DominatorTreeBase &Other) const {
318 if (Parent != Other.Parent) return true;
319
320 if (Roots.size() != Other.Roots.size())
321 return true;
322
323 if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin()))
324 return true;
325
326 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
327 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
328 return true;
329
330 for (const auto &DomTreeNode : DomTreeNodes) {
331 NodeT *BB = DomTreeNode.first;
332 typename DomTreeNodeMapType::const_iterator OI =
333 OtherDomTreeNodes.find(BB);
334 if (OI == OtherDomTreeNodes.end())
335 return true;
336
337 DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second;
338 DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
339
340 if (MyNd.compare(&OtherNd))
341 return true;
342 }
343
344 return false;
345 }
346
347 /// getNode - return the (Post)DominatorTree node for the specified basic
348 /// block. This is the same as using operator[] on this class. The result
349 /// may (but is not required to) be null for a forward (backwards)
350 /// statically unreachable block.
351 DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
352 auto I = DomTreeNodes.find(BB);
353 if (I != DomTreeNodes.end())
25
Calling 'operator!='
31
Returning from 'operator!='
32
Taking true branch
354 return I->second.get();
33
Returning pointer
355 return nullptr;
356 }
357
358 /// See getNode.
359 DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
360 return getNode(BB);
361 }
362
363 /// getRootNode - This returns the entry node for the CFG of the function. If
364 /// this tree represents the post-dominance relations for a function, however,
365 /// this root may be a node with the block == NULL. This is the case when
366 /// there are multiple exit nodes from a particular function. Consumers of
367 /// post-dominance information must be capable of dealing with this
368 /// possibility.
369 ///
370 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
371 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
372
373 /// Get all nodes dominated by R, including R itself.
374 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
375 Result.clear();
376 const DomTreeNodeBase<NodeT> *RN = getNode(R);
377 if (!RN)
378 return; // If R is unreachable, it will not be present in the DOM tree.
379 SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
380 WL.push_back(RN);
381
382 while (!WL.empty()) {
383 const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
384 Result.push_back(N->getBlock());
385 WL.append(N->begin(), N->end());
386 }
387 }
388
389 /// properlyDominates - Returns true iff A dominates B and A != B.
390 /// Note that this is not a constant time operation!
391 ///
392 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
393 const DomTreeNodeBase<NodeT> *B) const {
394 if (!A || !B)
395 return false;
396 if (A == B)
397 return false;
398 return dominates(A, B);
399 }
400
401 bool properlyDominates(const NodeT *A, const NodeT *B) const;
402
403 /// isReachableFromEntry - Return true if A is dominated by the entry
404 /// block of the function containing it.
405 bool isReachableFromEntry(const NodeT *A) const {
406 assert(!this->isPostDominator() &&((void)0)
407 "This is not implemented for post dominators")((void)0);
408 return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
409 }
410
411 bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
412
413 /// dominates - Returns true iff A dominates B. Note that this is not a
414 /// constant time operation!
415 ///
416 bool dominates(const DomTreeNodeBase<NodeT> *A,
417 const DomTreeNodeBase<NodeT> *B) const {
418 // A node trivially dominates itself.
419 if (B == A)
420 return true;
421
422 // An unreachable node is dominated by anything.
423 if (!isReachableFromEntry(B))
424 return true;
425
426 // And dominates nothing.
427 if (!isReachableFromEntry(A))
428 return false;
429
430 if (B->getIDom() == A) return true;
431
432 if (A->getIDom() == B) return false;
433
434 // A can only dominate B if it is higher in the tree.
435 if (A->getLevel() >= B->getLevel()) return false;
436
437 // Compare the result of the tree walk and the dfs numbers, if expensive
438 // checks are enabled.
439#ifdef EXPENSIVE_CHECKS
440 assert((!DFSInfoValid ||((void)0)
441 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&((void)0)
442 "Tree walk disagrees with dfs numbers!")((void)0);
443#endif
444
445 if (DFSInfoValid)
446 return B->DominatedBy(A);
447
448 // If we end up with too many slow queries, just update the
449 // DFS numbers on the theory that we are going to keep querying.
450 SlowQueries++;
451 if (SlowQueries > 32) {
452 updateDFSNumbers();
453 return B->DominatedBy(A);
454 }
455
456 return dominatedBySlowTreeWalk(A, B);
457 }
458
459 bool dominates(const NodeT *A, const NodeT *B) const;
460
461 NodeT *getRoot() const {
462 assert(this->Roots.size() == 1 && "Should always have entry node!")((void)0);
463 return this->Roots[0];
464 }
465
466 /// Find nearest common dominator basic block for basic block A and B. A and B
467 /// must have tree nodes.
468 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
469 assert(A && B && "Pointers are not valid")((void)0);
470 assert(A->getParent() == B->getParent() &&((void)0)
471 "Two blocks are not in same function")((void)0);
472
473 // If either A or B is a entry block then it is nearest common dominator
474 // (for forward-dominators).
475 if (!isPostDominator()) {
17
Calling 'DominatorTreeBase::isPostDominator'
19
Returning from 'DominatorTreeBase::isPostDominator'
20
Taking true branch
476 NodeT &Entry = A->getParent()->front();
477 if (A == &Entry || B == &Entry)
21
Assuming the condition is false
22
Assuming the condition is false
23
Taking false branch
478 return &Entry;
479 }
480
481 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
24
Calling 'DominatorTreeBase::getNode'
34
Returning from 'DominatorTreeBase::getNode'
35
'NodeA' initialized here
482 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
483 assert(NodeA && "A must be in the tree")((void)0);
484 assert(NodeB && "B must be in the tree")((void)0);
485
486 // Use level information to go up the tree until the levels match. Then
487 // continue going up til we arrive at the same node.
488 while (NodeA != NodeB) {
36
Assuming 'NodeA' is equal to 'NodeB'
37
Assuming pointer value is null
38
Loop condition is false. Execution continues on line 494
489 if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
490
491 NodeA = NodeA->IDom;
492 }
493
494 return NodeA->getBlock();
39
Called C++ object pointer is null
495 }
496
497 const NodeT *findNearestCommonDominator(const NodeT *A,
498 const NodeT *B) const {
499 // Cast away the const qualifiers here. This is ok since
500 // const is re-introduced on the return type.
501 return findNearestCommonDominator(const_cast<NodeT *>(A),
502 const_cast<NodeT *>(B));
503 }
504
505 bool isVirtualRoot(const DomTreeNodeBase<NodeT> *A) const {
506 return isPostDominator() && !A->getBlock();
507 }
508
509 //===--------------------------------------------------------------------===//
510 // API to update (Post)DominatorTree information based on modifications to
511 // the CFG...
512
513 /// Inform the dominator tree about a sequence of CFG edge insertions and
514 /// deletions and perform a batch update on the tree.
515 ///
516 /// This function should be used when there were multiple CFG updates after
517 /// the last dominator tree update. It takes care of performing the updates
518 /// in sync with the CFG and optimizes away the redundant operations that
519 /// cancel each other.
520 /// The functions expects the sequence of updates to be balanced. Eg.:
521 /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
522 /// logically it results in a single insertions.
523 /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
524 /// sense to insert the same edge twice.
525 ///
526 /// What's more, the functions assumes that it's safe to ask every node in the
527 /// CFG about its children and inverse children. This implies that deletions
528 /// of CFG edges must not delete the CFG nodes before calling this function.
529 ///
530 /// The applyUpdates function can reorder the updates and remove redundant
531 /// ones internally. The batch updater is also able to detect sequences of
532 /// zero and exactly one update -- it's optimized to do less work in these
533 /// cases.
534 ///
535 /// Note that for postdominators it automatically takes care of applying
536 /// updates on reverse edges internally (so there's no need to swap the
537 /// From and To pointers when constructing DominatorTree::UpdateType).
538 /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
539 /// with the same template parameter T.
540 ///
541 /// \param Updates An unordered sequence of updates to perform. The current
542 /// CFG and the reverse of these updates provides the pre-view of the CFG.
543 ///
544 void applyUpdates(ArrayRef<UpdateType> Updates) {
545 GraphDiff<NodePtr, IsPostDominator> PreViewCFG(
546 Updates, /*ReverseApplyUpdates=*/true);
547 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr);
548 }
549
550 /// \param Updates An unordered sequence of updates to perform. The current
551 /// CFG and the reverse of these updates provides the pre-view of the CFG.
552 /// \param PostViewUpdates An unordered sequence of update to perform in order
553 /// to obtain a post-view of the CFG. The DT will be updated assuming the
554 /// obtained PostViewCFG is the desired end state.
555 void applyUpdates(ArrayRef<UpdateType> Updates,
556 ArrayRef<UpdateType> PostViewUpdates) {
557 if (Updates.empty()) {
558 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
559 DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG);
560 } else {
561 // PreViewCFG needs to merge Updates and PostViewCFG. The updates in
562 // Updates need to be reversed, and match the direction in PostViewCFG.
563 // The PostViewCFG is created with updates reversed (equivalent to changes
564 // made to the CFG), so the PreViewCFG needs all the updates reverse
565 // applied.
566 SmallVector<UpdateType> AllUpdates(Updates.begin(), Updates.end());
567 append_range(AllUpdates, PostViewUpdates);
568 GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates,
569 /*ReverseApplyUpdates=*/true);
570 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
571 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG);
572 }
573 }
574
575 /// Inform the dominator tree about a CFG edge insertion and update the tree.
576 ///
577 /// This function has to be called just before or just after making the update
578 /// on the actual CFG. There cannot be any other updates that the dominator
579 /// tree doesn't know about.
580 ///
581 /// Note that for postdominators it automatically takes care of inserting
582 /// a reverse edge internally (so there's no need to swap the parameters).
583 ///
584 void insertEdge(NodeT *From, NodeT *To) {
585 assert(From)((void)0);
586 assert(To)((void)0);
587 assert(From->getParent() == Parent)((void)0);
588 assert(To->getParent() == Parent)((void)0);
589 DomTreeBuilder::InsertEdge(*this, From, To);
590 }
591
592 /// Inform the dominator tree about a CFG edge deletion and update the tree.
593 ///
594 /// This function has to be called just after making the update on the actual
595 /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
596 /// DEBUG mode. There cannot be any other updates that the
597 /// dominator tree doesn't know about.
598 ///
599 /// Note that for postdominators it automatically takes care of deleting
600 /// a reverse edge internally (so there's no need to swap the parameters).
601 ///
602 void deleteEdge(NodeT *From, NodeT *To) {
603 assert(From)((void)0);
604 assert(To)((void)0);
605 assert(From->getParent() == Parent)((void)0);
606 assert(To->getParent() == Parent)((void)0);
607 DomTreeBuilder::DeleteEdge(*this, From, To);
608 }
609
610 /// Add a new node to the dominator tree information.
611 ///
612 /// This creates a new node as a child of DomBB dominator node, linking it
613 /// into the children list of the immediate dominator.
614 ///
615 /// \param BB New node in CFG.
616 /// \param DomBB CFG node that is dominator for BB.
617 /// \returns New dominator tree node that represents new CFG node.
618 ///
619 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
620 assert(getNode(BB) == nullptr && "Block already in dominator tree!")((void)0);
621 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
622 assert(IDomNode && "Not immediate dominator specified for block!")((void)0);
623 DFSInfoValid = false;
624 return createChild(BB, IDomNode);
625 }
626
627 /// Add a new node to the forward dominator tree and make it a new root.
628 ///
629 /// \param BB New node in CFG.
630 /// \returns New dominator tree node that represents new CFG node.
631 ///
632 DomTreeNodeBase<NodeT> *setNewRoot(NodeT *BB) {
633 assert(getNode(BB) == nullptr && "Block already in dominator tree!")((void)0);
634 assert(!this->isPostDominator() &&((void)0)
635 "Cannot change root of post-dominator tree")((void)0);
636 DFSInfoValid = false;
637 DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
638 if (Roots.empty()) {
639 addRoot(BB);
640 } else {
641 assert(Roots.size() == 1)((void)0);
642 NodeT *OldRoot = Roots.front();
643 auto &OldNode = DomTreeNodes[OldRoot];
644 OldNode = NewNode->addChild(std::move(DomTreeNodes[OldRoot]));
645 OldNode->IDom = NewNode;
646 OldNode->UpdateLevel();
647 Roots[0] = BB;
648 }
649 return RootNode = NewNode;
650 }
651
652 /// changeImmediateDominator - This method is used to update the dominator
653 /// tree information when a node's immediate dominator changes.
654 ///
655 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
656 DomTreeNodeBase<NodeT> *NewIDom) {
657 assert(N && NewIDom && "Cannot change null node pointers!")((void)0);
658 DFSInfoValid = false;
659 N->setIDom(NewIDom);
660 }
661
662 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
663 changeImmediateDominator(getNode(BB), getNode(NewBB));
664 }
665
666 /// eraseNode - Removes a node from the dominator tree. Block must not
667 /// dominate any other blocks. Removes node from its immediate dominator's
668 /// children list. Deletes dominator node associated with basic block BB.
669 void eraseNode(NodeT *BB) {
670 DomTreeNodeBase<NodeT> *Node = getNode(BB);
671 assert(Node && "Removing node that isn't in dominator tree.")((void)0);
672 assert(Node->isLeaf() && "Node is not a leaf node.")((void)0);
673
674 DFSInfoValid = false;
675
676 // Remove node from immediate dominator's children list.
677 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
678 if (IDom) {
679 const auto I = find(IDom->Children, Node);
680 assert(I != IDom->Children.end() &&((void)0)
681 "Not in immediate dominator children set!")((void)0);
682 // I am no longer your child...
683 IDom->Children.erase(I);
684 }
685
686 DomTreeNodes.erase(BB);
687
688 if (!IsPostDom) return;
689
690 // Remember to update PostDominatorTree roots.
691 auto RIt = llvm::find(Roots, BB);
692 if (RIt != Roots.end()) {
693 std::swap(*RIt, Roots.back());
694 Roots.pop_back();
695 }
696 }
697
698 /// splitBlock - BB is split and now it has one successor. Update dominator
699 /// tree to reflect this change.
700 void splitBlock(NodeT *NewBB) {
701 if (IsPostDominator)
702 Split<Inverse<NodeT *>>(NewBB);
703 else
704 Split<NodeT *>(NewBB);
705 }
706
707 /// print - Convert to human readable form
708 ///
709 void print(raw_ostream &O) const {
710 O << "=============================--------------------------------\n";
711 if (IsPostDominator)
712 O << "Inorder PostDominator Tree: ";
713 else
714 O << "Inorder Dominator Tree: ";
715 if (!DFSInfoValid)
716 O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
717 O << "\n";
718
719 // The postdom tree can have a null root if there are no returns.
720 if (getRootNode()) PrintDomTree<NodeT>(getRootNode(), O, 1);
721 O << "Roots: ";
722 for (const NodePtr Block : Roots) {
723 Block->printAsOperand(O, false);
724 O << " ";
725 }
726 O << "\n";
727 }
728
729public:
730 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
731 /// dominator tree in dfs order.
732 void updateDFSNumbers() const {
733 if (DFSInfoValid) {
734 SlowQueries = 0;
735 return;
736 }
737
738 SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
739 typename DomTreeNodeBase<NodeT>::const_iterator>,
740 32> WorkStack;
741
742 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
743 assert((!Parent || ThisRoot) && "Empty constructed DomTree")((void)0);
744 if (!ThisRoot)
745 return;
746
747 // Both dominators and postdominators have a single root node. In the case
748 // case of PostDominatorTree, this node is a virtual root.
749 WorkStack.push_back({ThisRoot, ThisRoot->begin()});
750
751 unsigned DFSNum = 0;
752 ThisRoot->DFSNumIn = DFSNum++;
753
754 while (!WorkStack.empty()) {
755 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
756 const auto ChildIt = WorkStack.back().second;
757
758 // If we visited all of the children of this node, "recurse" back up the
759 // stack setting the DFOutNum.
760 if (ChildIt == Node->end()) {
761 Node->DFSNumOut = DFSNum++;
762 WorkStack.pop_back();
763 } else {
764 // Otherwise, recursively visit this child.
765 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
766 ++WorkStack.back().second;
767
768 WorkStack.push_back({Child, Child->begin()});
769 Child->DFSNumIn = DFSNum++;
770 }
771 }
772
773 SlowQueries = 0;
774 DFSInfoValid = true;
775 }
776
777 /// recalculate - compute a dominator tree for the given function
778 void recalculate(ParentType &Func) {
779 Parent = &Func;
780 DomTreeBuilder::Calculate(*this);
781 }
782
783 void recalculate(ParentType &Func, ArrayRef<UpdateType> Updates) {
784 Parent = &Func;
785 DomTreeBuilder::CalculateWithUpdates(*this, Updates);
786 }
787
788 /// verify - checks if the tree is correct. There are 3 level of verification:
789 /// - Full -- verifies if the tree is correct by making sure all the
790 /// properties (including the parent and the sibling property)
791 /// hold.
792 /// Takes O(N^3) time.
793 ///
794 /// - Basic -- checks if the tree is correct, but compares it to a freshly
795 /// constructed tree instead of checking the sibling property.
796 /// Takes O(N^2) time.
797 ///
798 /// - Fast -- checks basic tree structure and compares it with a freshly
799 /// constructed tree.
800 /// Takes O(N^2) time worst case, but is faster in practise (same
801 /// as tree construction).
802 bool verify(VerificationLevel VL = VerificationLevel::Full) const {
803 return DomTreeBuilder::Verify(*this, VL);
804 }
805
806 void reset() {
807 DomTreeNodes.clear();
808 Roots.clear();
809 RootNode = nullptr;
810 Parent = nullptr;
811 DFSInfoValid = false;
812 SlowQueries = 0;
813 }
814
815protected:
816 void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
817
818 DomTreeNodeBase<NodeT> *createChild(NodeT *BB, DomTreeNodeBase<NodeT> *IDom) {
819 return (DomTreeNodes[BB] = IDom->addChild(
820 std::make_unique<DomTreeNodeBase<NodeT>>(BB, IDom)))
821 .get();
822 }
823
824 DomTreeNodeBase<NodeT> *createNode(NodeT *BB) {
825 return (DomTreeNodes[BB] =
826 std::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr))
827 .get();
828 }
829
830 // NewBB is split and now it has one successor. Update dominator tree to
831 // reflect this change.
832 template <class N>
833 void Split(typename GraphTraits<N>::NodeRef NewBB) {
834 using GraphT = GraphTraits<N>;
835 using NodeRef = typename GraphT::NodeRef;
836 assert(std::distance(GraphT::child_begin(NewBB),((void)0)
837 GraphT::child_end(NewBB)) == 1 &&((void)0)
838 "NewBB should have a single successor!")((void)0);
839 NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
840
841 SmallVector<NodeRef, 4> PredBlocks(children<Inverse<N>>(NewBB));
842
843 assert(!PredBlocks.empty() && "No predblocks?")((void)0);
844
845 bool NewBBDominatesNewBBSucc = true;
846 for (auto Pred : children<Inverse<N>>(NewBBSucc)) {
847 if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
848 isReachableFromEntry(Pred)) {
849 NewBBDominatesNewBBSucc = false;
850 break;
851 }
852 }
853
854 // Find NewBB's immediate dominator and create new dominator tree node for
855 // NewBB.
856 NodeT *NewBBIDom = nullptr;
857 unsigned i = 0;
858 for (i = 0; i < PredBlocks.size(); ++i)
859 if (isReachableFromEntry(PredBlocks[i])) {
860 NewBBIDom = PredBlocks[i];
861 break;
862 }
863
864 // It's possible that none of the predecessors of NewBB are reachable;
865 // in that case, NewBB itself is unreachable, so nothing needs to be
866 // changed.
867 if (!NewBBIDom) return;
868
869 for (i = i + 1; i < PredBlocks.size(); ++i) {
870 if (isReachableFromEntry(PredBlocks[i]))
871 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
872 }
873
874 // Create the new dominator tree node... and set the idom of NewBB.
875 DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
876
877 // If NewBB strictly dominates other blocks, then it is now the immediate
878 // dominator of NewBBSucc. Update the dominator tree as appropriate.
879 if (NewBBDominatesNewBBSucc) {
880 DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
881 changeImmediateDominator(NewBBSuccNode, NewBBNode);
882 }
883 }
884
885 private:
886 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
887 const DomTreeNodeBase<NodeT> *B) const {
888 assert(A != B)((void)0);
889 assert(isReachableFromEntry(B))((void)0);
890 assert(isReachableFromEntry(A))((void)0);
891
892 const unsigned ALevel = A->getLevel();
893 const DomTreeNodeBase<NodeT> *IDom;
894
895 // Don't walk nodes above A's subtree. When we reach A's level, we must
896 // either find A or be in some other subtree not dominated by A.
897 while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
898 B = IDom; // Walk up the tree
899
900 return B == A;
901 }
902
903 /// Wipe this tree's state without releasing any resources.
904 ///
905 /// This is essentially a post-move helper only. It leaves the object in an
906 /// assignable and destroyable state, but otherwise invalid.
907 void wipe() {
908 DomTreeNodes.clear();
909 RootNode = nullptr;
910 Parent = nullptr;
911 }
912};
913
914template <typename T>
915using DomTreeBase = DominatorTreeBase<T, false>;
916
917template <typename T>
918using PostDomTreeBase = DominatorTreeBase<T, true>;
919
920// These two functions are declared out of line as a workaround for building
921// with old (< r147295) versions of clang because of pr11642.
922template <typename NodeT, bool IsPostDom>
923bool DominatorTreeBase<NodeT, IsPostDom>::dominates(const NodeT *A,
924 const NodeT *B) const {
925 if (A == B)
926 return true;
927
928 // Cast away the const qualifiers here. This is ok since
929 // this function doesn't actually return the values returned
930 // from getNode.
931 return dominates(getNode(const_cast<NodeT *>(A)),
932 getNode(const_cast<NodeT *>(B)));
933}
934template <typename NodeT, bool IsPostDom>
935bool DominatorTreeBase<NodeT, IsPostDom>::properlyDominates(
936 const NodeT *A, const NodeT *B) const {
937 if (A == B)
938 return false;
939
940 // Cast away the const qualifiers here. This is ok since
941 // this function doesn't actually return the values returned
942 // from getNode.
943 return dominates(getNode(const_cast<NodeT *>(A)),
944 getNode(const_cast<NodeT *>(B)));
945}
946
947} // end namespace llvm
948
949#endif // LLVM_SUPPORT_GENERICDOMTREE_H

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT/DenseMap.h

1//===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the DenseMap class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_DENSEMAP_H
14#define LLVM_ADT_DENSEMAP_H
15
16#include "llvm/ADT/DenseMapInfo.h"
17#include "llvm/ADT/EpochTracker.h"
18#include "llvm/Support/AlignOf.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/MathExtras.h"
21#include "llvm/Support/MemAlloc.h"
22#include "llvm/Support/ReverseIteration.h"
23#include "llvm/Support/type_traits.h"
24#include <algorithm>
25#include <cassert>
26#include <cstddef>
27#include <cstring>
28#include <initializer_list>
29#include <iterator>
30#include <new>
31#include <type_traits>
32#include <utility>
33
34namespace llvm {
35
36namespace detail {
37
38// We extend a pair to allow users to override the bucket type with their own
39// implementation without requiring two members.
40template <typename KeyT, typename ValueT>
41struct DenseMapPair : public std::pair<KeyT, ValueT> {
42 using std::pair<KeyT, ValueT>::pair;
43
44 KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
45 const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
46 ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
47 const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
48};
49
50} // end namespace detail
51
52template <typename KeyT, typename ValueT,
53 typename KeyInfoT = DenseMapInfo<KeyT>,
54 typename Bucket = llvm::detail::DenseMapPair<KeyT, ValueT>,
55 bool IsConst = false>
56class DenseMapIterator;
57
58template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
59 typename BucketT>
60class DenseMapBase : public DebugEpochBase {
61 template <typename T>
62 using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
63
64public:
65 using size_type = unsigned;
66 using key_type = KeyT;
67 using mapped_type = ValueT;
68 using value_type = BucketT;
69
70 using iterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT>;
71 using const_iterator =
72 DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>;
73
74 inline iterator begin() {
75 // When the map is empty, avoid the overhead of advancing/retreating past
76 // empty buckets.
77 if (empty())
78 return end();
79 if (shouldReverseIterate<KeyT>())
80 return makeIterator(getBucketsEnd() - 1, getBuckets(), *this);
81 return makeIterator(getBuckets(), getBucketsEnd(), *this);
82 }
83 inline iterator end() {
84 return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
85 }
86 inline const_iterator begin() const {
87 if (empty())
88 return end();
89 if (shouldReverseIterate<KeyT>())
90 return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this);
91 return makeConstIterator(getBuckets(), getBucketsEnd(), *this);
92 }
93 inline const_iterator end() const {
94 return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
95 }
96
97 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const {
98 return getNumEntries() == 0;
99 }
100 unsigned size() const { return getNumEntries(); }
101
102 /// Grow the densemap so that it can contain at least \p NumEntries items
103 /// before resizing again.
104 void reserve(size_type NumEntries) {
105 auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
106 incrementEpoch();
107 if (NumBuckets > getNumBuckets())
108 grow(NumBuckets);
109 }
110
111 void clear() {
112 incrementEpoch();
113 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
114
115 // If the capacity of the array is huge, and the # elements used is small,
116 // shrink the array.
117 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
118 shrink_and_clear();
119 return;
120 }
121
122 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
123 if (std::is_trivially_destructible<ValueT>::value) {
124 // Use a simpler loop when values don't need destruction.
125 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
126 P->getFirst() = EmptyKey;
127 } else {
128 unsigned NumEntries = getNumEntries();
129 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
130 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
131 if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
132 P->getSecond().~ValueT();
133 --NumEntries;
134 }
135 P->getFirst() = EmptyKey;
136 }
137 }
138 assert(NumEntries == 0 && "Node count imbalance!")((void)0);
139 }
140 setNumEntries(0);
141 setNumTombstones(0);
142 }
143
144 /// Return 1 if the specified key is in the map, 0 otherwise.
145 size_type count(const_arg_type_t<KeyT> Val) const {
146 const BucketT *TheBucket;
147 return LookupBucketFor(Val, TheBucket) ? 1 : 0;
148 }
149
150 iterator find(const_arg_type_t<KeyT> Val) {
151 BucketT *TheBucket;
152 if (LookupBucketFor(Val, TheBucket))
153 return makeIterator(TheBucket,
154 shouldReverseIterate<KeyT>() ? getBuckets()
155 : getBucketsEnd(),
156 *this, true);
157 return end();
158 }
159 const_iterator find(const_arg_type_t<KeyT> Val) const {
160 const BucketT *TheBucket;
161 if (LookupBucketFor(Val, TheBucket))
162 return makeConstIterator(TheBucket,
163 shouldReverseIterate<KeyT>() ? getBuckets()
164 : getBucketsEnd(),
165 *this, true);
166 return end();
167 }
168
169 /// Alternate version of find() which allows a different, and possibly
170 /// less expensive, key type.
171 /// The DenseMapInfo is responsible for supplying methods
172 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
173 /// type used.
174 template<class LookupKeyT>
175 iterator find_as(const LookupKeyT &Val) {
176 BucketT *TheBucket;
177 if (LookupBucketFor(Val, TheBucket))
178 return makeIterator(TheBucket,
179 shouldReverseIterate<KeyT>() ? getBuckets()
180 : getBucketsEnd(),
181 *this, true);
182 return end();
183 }
184 template<class LookupKeyT>
185 const_iterator find_as(const LookupKeyT &Val) const {
186 const BucketT *TheBucket;
187 if (LookupBucketFor(Val, TheBucket))
188 return makeConstIterator(TheBucket,
189 shouldReverseIterate<KeyT>() ? getBuckets()
190 : getBucketsEnd(),
191 *this, true);
192 return end();
193 }
194
195 /// lookup - Return the entry for the specified key, or a default
196 /// constructed value if no such entry exists.
197 ValueT lookup(const_arg_type_t<KeyT> Val) const {
198 const BucketT *TheBucket;
199 if (LookupBucketFor(Val, TheBucket))
200 return TheBucket->getSecond();
201 return ValueT();
202 }
203
204 // Inserts key,value pair into the map if the key isn't already in the map.
205 // If the key is already in the map, it returns false and doesn't update the
206 // value.
207 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
208 return try_emplace(KV.first, KV.second);
209 }
210
211 // Inserts key,value pair into the map if the key isn't already in the map.
212 // If the key is already in the map, it returns false and doesn't update the
213 // value.
214 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
215 return try_emplace(std::move(KV.first), std::move(KV.second));
216 }
217
218 // Inserts key,value pair into the map if the key isn't already in the map.
219 // The value is constructed in-place if the key is not in the map, otherwise
220 // it is not moved.
221 template <typename... Ts>
222 std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
223 BucketT *TheBucket;
224 if (LookupBucketFor(Key, TheBucket))
225 return std::make_pair(makeIterator(TheBucket,
226 shouldReverseIterate<KeyT>()
227 ? getBuckets()
228 : getBucketsEnd(),
229 *this, true),
230 false); // Already in map.
231
232 // Otherwise, insert the new element.
233 TheBucket =
234 InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
235 return std::make_pair(makeIterator(TheBucket,
236 shouldReverseIterate<KeyT>()
237 ? getBuckets()
238 : getBucketsEnd(),
239 *this, true),
240 true);
241 }
242
243 // Inserts key,value pair into the map if the key isn't already in the map.
244 // The value is constructed in-place if the key is not in the map, otherwise
245 // it is not moved.
246 template <typename... Ts>
247 std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
248 BucketT *TheBucket;
249 if (LookupBucketFor(Key, TheBucket))
250 return std::make_pair(makeIterator(TheBucket,
251 shouldReverseIterate<KeyT>()
252 ? getBuckets()
253 : getBucketsEnd(),
254 *this, true),
255 false); // Already in map.
256
257 // Otherwise, insert the new element.
258 TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
259 return std::make_pair(makeIterator(TheBucket,
260 shouldReverseIterate<KeyT>()
261 ? getBuckets()
262 : getBucketsEnd(),
263 *this, true),
264 true);
265 }
266
267 /// Alternate version of insert() which allows a different, and possibly
268 /// less expensive, key type.
269 /// The DenseMapInfo is responsible for supplying methods
270 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
271 /// type used.
272 template <typename LookupKeyT>
273 std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
274 const LookupKeyT &Val) {
275 BucketT *TheBucket;
276 if (LookupBucketFor(Val, TheBucket))
277 return std::make_pair(makeIterator(TheBucket,
278 shouldReverseIterate<KeyT>()
279 ? getBuckets()
280 : getBucketsEnd(),
281 *this, true),
282 false); // Already in map.
283
284 // Otherwise, insert the new element.
285 TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
286 std::move(KV.second), Val);
287 return std::make_pair(makeIterator(TheBucket,
288 shouldReverseIterate<KeyT>()
289 ? getBuckets()
290 : getBucketsEnd(),
291 *this, true),
292 true);
293 }
294
295 /// insert - Range insertion of pairs.
296 template<typename InputIt>
297 void insert(InputIt I, InputIt E) {
298 for (; I != E; ++I)
299 insert(*I);
300 }
301
302 bool erase(const KeyT &Val) {
303 BucketT *TheBucket;
304 if (!LookupBucketFor(Val, TheBucket))
305 return false; // not in map.
306
307 TheBucket->getSecond().~ValueT();
308 TheBucket->getFirst() = getTombstoneKey();
309 decrementNumEntries();
310 incrementNumTombstones();
311 return true;
312 }
313 void erase(iterator I) {
314 BucketT *TheBucket = &*I;
315 TheBucket->getSecond().~ValueT();
316 TheBucket->getFirst() = getTombstoneKey();
317 decrementNumEntries();
318 incrementNumTombstones();
319 }
320
321 value_type& FindAndConstruct(const KeyT &Key) {
322 BucketT *TheBucket;
323 if (LookupBucketFor(Key, TheBucket))
324 return *TheBucket;
325
326 return *InsertIntoBucket(TheBucket, Key);
327 }
328
329 ValueT &operator[](const KeyT &Key) {
330 return FindAndConstruct(Key).second;
331 }
332
333 value_type& FindAndConstruct(KeyT &&Key) {
334 BucketT *TheBucket;
335 if (LookupBucketFor(Key, TheBucket))
336 return *TheBucket;
337
338 return *InsertIntoBucket(TheBucket, std::move(Key));
339 }
340
341 ValueT &operator[](KeyT &&Key) {
342 return FindAndConstruct(std::move(Key)).second;
343 }
344
345 /// isPointerIntoBucketsArray - Return true if the specified pointer points
346 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
347 /// value in the DenseMap).
348 bool isPointerIntoBucketsArray(const void *Ptr) const {
349 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
350 }
351
352 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
353 /// array. In conjunction with the previous method, this can be used to
354 /// determine whether an insertion caused the DenseMap to reallocate.
355 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
356
357protected:
358 DenseMapBase() = default;
359
360 void destroyAll() {
361 if (getNumBuckets() == 0) // Nothing to do.
362 return;
363
364 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
365 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
366 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
367 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
368 P->getSecond().~ValueT();
369 P->getFirst().~KeyT();
370 }
371 }
372
373 void initEmpty() {
374 setNumEntries(0);
375 setNumTombstones(0);
376
377 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&((void)0)
378 "# initial buckets must be a power of two!")((void)0);
379 const KeyT EmptyKey = getEmptyKey();
380 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
381 ::new (&B->getFirst()) KeyT(EmptyKey);
382 }
383
384 /// Returns the number of buckets to allocate to ensure that the DenseMap can
385 /// accommodate \p NumEntries without need to grow().
386 unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
387 // Ensure that "NumEntries * 4 < NumBuckets * 3"
388 if (NumEntries == 0)
389 return 0;
390 // +1 is required because of the strict equality.
391 // For example if NumEntries is 48, we need to return 401.
392 return NextPowerOf2(NumEntries * 4 / 3 + 1);
393 }
394
395 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
396 initEmpty();
397
398 // Insert all the old elements.
399 const KeyT EmptyKey = getEmptyKey();
400 const KeyT TombstoneKey = getTombstoneKey();
401 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
402 if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
403 !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
404 // Insert the key/value into the new table.
405 BucketT *DestBucket;
406 bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
407 (void)FoundVal; // silence warning.
408 assert(!FoundVal && "Key already in new map?")((void)0);
409 DestBucket->getFirst() = std::move(B->getFirst());
410 ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
411 incrementNumEntries();
412
413 // Free the value.
414 B->getSecond().~ValueT();
415 }
416 B->getFirst().~KeyT();
417 }
418 }
419
420 template <typename OtherBaseT>
421 void copyFrom(
422 const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
423 assert(&other != this)((void)0);
424 assert(getNumBuckets() == other.getNumBuckets())((void)0);
425
426 setNumEntries(other.getNumEntries());
427 setNumTombstones(other.getNumTombstones());
428
429 if (std::is_trivially_copyable<KeyT>::value &&
430 std::is_trivially_copyable<ValueT>::value)
431 memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
432 getNumBuckets() * sizeof(BucketT));
433 else
434 for (size_t i = 0; i < getNumBuckets(); ++i) {
435 ::new (&getBuckets()[i].getFirst())
436 KeyT(other.getBuckets()[i].getFirst());
437 if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
438 !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
439 ::new (&getBuckets()[i].getSecond())
440 ValueT(other.getBuckets()[i].getSecond());
441 }
442 }
443
444 static unsigned getHashValue(const KeyT &Val) {
445 return KeyInfoT::getHashValue(Val);
446 }
447
448 template<typename LookupKeyT>
449 static unsigned getHashValue(const LookupKeyT &Val) {
450 return KeyInfoT::getHashValue(Val);
451 }
452
453 static const KeyT getEmptyKey() {
454 static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
455 "Must pass the derived type to this template!");
456 return KeyInfoT::getEmptyKey();
457 }
458
459 static const KeyT getTombstoneKey() {
460 return KeyInfoT::getTombstoneKey();
461 }
462
463private:
464 iterator makeIterator(BucketT *P, BucketT *E,
465 DebugEpochBase &Epoch,
466 bool NoAdvance=false) {
467 if (shouldReverseIterate<KeyT>()) {
468 BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
469 return iterator(B, E, Epoch, NoAdvance);
470 }
471 return iterator(P, E, Epoch, NoAdvance);
472 }
473
474 const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
475 const DebugEpochBase &Epoch,
476 const bool NoAdvance=false) const {
477 if (shouldReverseIterate<KeyT>()) {
478 const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
479 return const_iterator(B, E, Epoch, NoAdvance);
480 }
481 return const_iterator(P, E, Epoch, NoAdvance);
482 }
483
484 unsigned getNumEntries() const {
485 return static_cast<const DerivedT *>(this)->getNumEntries();
486 }
487
488 void setNumEntries(unsigned Num) {
489 static_cast<DerivedT *>(this)->setNumEntries(Num);
490 }
491
492 void incrementNumEntries() {
493 setNumEntries(getNumEntries() + 1);
494 }
495
496 void decrementNumEntries() {
497 setNumEntries(getNumEntries() - 1);
498 }
499
500 unsigned getNumTombstones() const {
501 return static_cast<const DerivedT *>(this)->getNumTombstones();
502 }
503
504 void setNumTombstones(unsigned Num) {
505 static_cast<DerivedT *>(this)->setNumTombstones(Num);
506 }
507
508 void incrementNumTombstones() {
509 setNumTombstones(getNumTombstones() + 1);
510 }
511
512 void decrementNumTombstones() {
513 setNumTombstones(getNumTombstones() - 1);
514 }
515
516 const BucketT *getBuckets() const {
517 return static_cast<const DerivedT *>(this)->getBuckets();
518 }
519
520 BucketT *getBuckets() {
521 return static_cast<DerivedT *>(this)->getBuckets();
522 }
523
524 unsigned getNumBuckets() const {
525 return static_cast<const DerivedT *>(this)->getNumBuckets();
526 }
527
528 BucketT *getBucketsEnd() {
529 return getBuckets() + getNumBuckets();
530 }
531
532 const BucketT *getBucketsEnd() const {
533 return getBuckets() + getNumBuckets();
534 }
535
536 void grow(unsigned AtLeast) {
537 static_cast<DerivedT *>(this)->grow(AtLeast);
538 }
539
540 void shrink_and_clear() {
541 static_cast<DerivedT *>(this)->shrink_and_clear();
542 }
543
544 template <typename KeyArg, typename... ValueArgs>
545 BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
546 ValueArgs &&... Values) {
547 TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
548
549 TheBucket->getFirst() = std::forward<KeyArg>(Key);
550 ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
551 return TheBucket;
552 }
553
554 template <typename LookupKeyT>
555 BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
556 ValueT &&Value, LookupKeyT &Lookup) {
557 TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
558
559 TheBucket->getFirst() = std::move(Key);
560 ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
561 return TheBucket;
562 }
563
564 template <typename LookupKeyT>
565 BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
566 BucketT *TheBucket) {
567 incrementEpoch();
568
569 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
570 // the buckets are empty (meaning that many are filled with tombstones),
571 // grow the table.
572 //
573 // The later case is tricky. For example, if we had one empty bucket with
574 // tons of tombstones, failing lookups (e.g. for insertion) would have to
575 // probe almost the entire table until it found the empty bucket. If the
576 // table completely filled with tombstones, no lookup would ever succeed,
577 // causing infinite loops in lookup.
578 unsigned NewNumEntries = getNumEntries() + 1;
579 unsigned NumBuckets = getNumBuckets();
580 if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)__builtin_expect((bool)(NewNumEntries * 4 >= NumBuckets * 3
), false)
) {
581 this->grow(NumBuckets * 2);
582 LookupBucketFor(Lookup, TheBucket);
583 NumBuckets = getNumBuckets();
584 } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=__builtin_expect((bool)(NumBuckets-(NewNumEntries+getNumTombstones
()) <= NumBuckets/8), false)
585 NumBuckets/8)__builtin_expect((bool)(NumBuckets-(NewNumEntries+getNumTombstones
()) <= NumBuckets/8), false)
) {
586 this->grow(NumBuckets);
587 LookupBucketFor(Lookup, TheBucket);
588 }
589 assert(TheBucket)((void)0);
590
591 // Only update the state after we've grown our bucket space appropriately
592 // so that when growing buckets we have self-consistent entry count.
593 incrementNumEntries();
594
595 // If we are writing over a tombstone, remember this.
596 const KeyT EmptyKey = getEmptyKey();
597 if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
598 decrementNumTombstones();
599
600 return TheBucket;
601 }
602
603 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
604 /// FoundBucket. If the bucket contains the key and a value, this returns
605 /// true, otherwise it returns a bucket with an empty marker or tombstone and
606 /// returns false.
607 template<typename LookupKeyT>
608 bool LookupBucketFor(const LookupKeyT &Val,
609 const BucketT *&FoundBucket) const {
610 const BucketT *BucketsPtr = getBuckets();
611 const unsigned NumBuckets = getNumBuckets();
612
613 if (NumBuckets == 0) {
614 FoundBucket = nullptr;
615 return false;
616 }
617
618 // FoundTombstone - Keep track of whether we find a tombstone while probing.
619 const BucketT *FoundTombstone = nullptr;
620 const KeyT EmptyKey = getEmptyKey();
621 const KeyT TombstoneKey = getTombstoneKey();
622 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&((void)0)
623 !KeyInfoT::isEqual(Val, TombstoneKey) &&((void)0)
624 "Empty/Tombstone value shouldn't be inserted into map!")((void)0);
625
626 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
627 unsigned ProbeAmt = 1;
628 while (true) {
629 const BucketT *ThisBucket = BucketsPtr + BucketNo;
630 // Found Val's bucket? If so, return it.
631 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))__builtin_expect((bool)(KeyInfoT::isEqual(Val, ThisBucket->
getFirst())), true)
) {
632 FoundBucket = ThisBucket;
633 return true;
634 }
635
636 // If we found an empty bucket, the key doesn't exist in the set.
637 // Insert it and return the default value.
638 if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))__builtin_expect((bool)(KeyInfoT::isEqual(ThisBucket->getFirst
(), EmptyKey)), true)
) {
639 // If we've already seen a tombstone while probing, fill it in instead
640 // of the empty bucket we eventually probed to.
641 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
642 return false;
643 }
644
645 // If this is a tombstone, remember it. If Val ends up not in the map, we
646 // prefer to return it than something that would require more probing.
647 if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
648 !FoundTombstone)
649 FoundTombstone = ThisBucket; // Remember the first tombstone found.
650
651 // Otherwise, it's a hash collision or a tombstone, continue quadratic
652 // probing.
653 BucketNo += ProbeAmt++;
654 BucketNo &= (NumBuckets-1);
655 }
656 }
657
658 template <typename LookupKeyT>
659 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
660 const BucketT *ConstFoundBucket;
661 bool Result = const_cast<const DenseMapBase *>(this)
662 ->LookupBucketFor(Val, ConstFoundBucket);
663 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
664 return Result;
665 }
666
667public:
668 /// Return the approximate size (in bytes) of the actual map.
669 /// This is just the raw memory used by DenseMap.
670 /// If entries are pointers to objects, the size of the referenced objects
671 /// are not included.
672 size_t getMemorySize() const {
673 return getNumBuckets() * sizeof(BucketT);
674 }
675};
676
677/// Equality comparison for DenseMap.
678///
679/// Iterates over elements of LHS confirming that each (key, value) pair in LHS
680/// is also in RHS, and that no additional pairs are in RHS.
681/// Equivalent to N calls to RHS.find and N value comparisons. Amortized
682/// complexity is linear, worst case is O(N^2) (if every hash collides).
683template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
684 typename BucketT>
685bool operator==(
686 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
687 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
688 if (LHS.size() != RHS.size())
689 return false;
690
691 for (auto &KV : LHS) {
692 auto I = RHS.find(KV.first);
693 if (I == RHS.end() || I->second != KV.second)
694 return false;
695 }
696
697 return true;
698}
699
700/// Inequality comparison for DenseMap.
701///
702/// Equivalent to !(LHS == RHS). See operator== for performance notes.
703template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
704 typename BucketT>
705bool operator!=(
706 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
707 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
708 return !(LHS == RHS);
709}
710
711template <typename KeyT, typename ValueT,
712 typename KeyInfoT = DenseMapInfo<KeyT>,
713 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
714class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
715 KeyT, ValueT, KeyInfoT, BucketT> {
716 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
717
718 // Lift some types from the dependent base class into this class for
719 // simplicity of referring to them.
720 using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
721
722 BucketT *Buckets;
723 unsigned NumEntries;
724 unsigned NumTombstones;
725 unsigned NumBuckets;
726
727public:
728 /// Create a DenseMap with an optional \p InitialReserve that guarantee that
729 /// this number of elements can be inserted in the map without grow()
730 explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
731
732 DenseMap(const DenseMap &other) : BaseT() {
733 init(0);
734 copyFrom(other);
735 }
736
737 DenseMap(DenseMap &&other) : BaseT() {
738 init(0);
739 swap(other);
740 }
741
742 template<typename InputIt>
743 DenseMap(const InputIt &I, const InputIt &E) {
744 init(std::distance(I, E));
745 this->insert(I, E);
746 }
747
748 DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
749 init(Vals.size());
750 this->insert(Vals.begin(), Vals.end());
751 }
752
753 ~DenseMap() {
754 this->destroyAll();
755 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
756 }
757
758 void swap(DenseMap& RHS) {
759 this->incrementEpoch();
760 RHS.incrementEpoch();
761 std::swap(Buckets, RHS.Buckets);
762 std::swap(NumEntries, RHS.NumEntries);
763 std::swap(NumTombstones, RHS.NumTombstones);
764 std::swap(NumBuckets, RHS.NumBuckets);
765 }
766
767 DenseMap& operator=(const DenseMap& other) {
768 if (&other != this)
769 copyFrom(other);
770 return *this;
771 }
772
773 DenseMap& operator=(DenseMap &&other) {
774 this->destroyAll();
775 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
776 init(0);
777 swap(other);
778 return *this;
779 }
780
781 void copyFrom(const DenseMap& other) {
782 this->destroyAll();
783 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
784 if (allocateBuckets(other.NumBuckets)) {
785 this->BaseT::copyFrom(other);
786 } else {
787 NumEntries = 0;
788 NumTombstones = 0;
789 }
790 }
791
792 void init(unsigned InitNumEntries) {
793 auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
794 if (allocateBuckets(InitBuckets)) {
795 this->BaseT::initEmpty();
796 } else {
797 NumEntries = 0;
798 NumTombstones = 0;
799 }
800 }
801
802 void grow(unsigned AtLeast) {
803 unsigned OldNumBuckets = NumBuckets;
804 BucketT *OldBuckets = Buckets;
805
806 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
807 assert(Buckets)((void)0);
808 if (!OldBuckets) {
809 this->BaseT::initEmpty();
810 return;
811 }
812
813 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
814
815 // Free the old table.
816 deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets,
817 alignof(BucketT));
818 }
819
820 void shrink_and_clear() {
821 unsigned OldNumBuckets = NumBuckets;
822 unsigned OldNumEntries = NumEntries;
823 this->destroyAll();
824
825 // Reduce the number of buckets.
826 unsigned NewNumBuckets = 0;
827 if (OldNumEntries)
828 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
829 if (NewNumBuckets == NumBuckets) {
830 this->BaseT::initEmpty();
831 return;
832 }
833
834 deallocate_buffer(Buckets, sizeof(BucketT) * OldNumBuckets,
835 alignof(BucketT));
836 init(NewNumBuckets);
837 }
838
839private:
840 unsigned getNumEntries() const {
841 return NumEntries;
842 }
843
844 void setNumEntries(unsigned Num) {
845 NumEntries = Num;
846 }
847
848 unsigned getNumTombstones() const {
849 return NumTombstones;
850 }
851
852 void setNumTombstones(unsigned Num) {
853 NumTombstones = Num;
854 }
855
856 BucketT *getBuckets() const {
857 return Buckets;
858 }
859
860 unsigned getNumBuckets() const {
861 return NumBuckets;
862 }
863
864 bool allocateBuckets(unsigned Num) {
865 NumBuckets = Num;
866 if (NumBuckets == 0) {
867 Buckets = nullptr;
868 return false;
869 }
870
871 Buckets = static_cast<BucketT *>(
872 allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT)));
873 return true;
874 }
875};
876
877template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
878 typename KeyInfoT = DenseMapInfo<KeyT>,
879 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
880class SmallDenseMap
881 : public DenseMapBase<
882 SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
883 ValueT, KeyInfoT, BucketT> {
884 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
885
886 // Lift some types from the dependent base class into this class for
887 // simplicity of referring to them.
888 using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
889
890 static_assert(isPowerOf2_64(InlineBuckets),
891 "InlineBuckets must be a power of 2.");
892
893 unsigned Small : 1;
894 unsigned NumEntries : 31;
895 unsigned NumTombstones;
896
897 struct LargeRep {
898 BucketT *Buckets;
899 unsigned NumBuckets;
900 };
901
902 /// A "union" of an inline bucket array and the struct representing
903 /// a large bucket. This union will be discriminated by the 'Small' bit.
904 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
905
906public:
907 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
908 init(NumInitBuckets);
909 }
910
911 SmallDenseMap(const SmallDenseMap &other) : BaseT() {
912 init(0);
913 copyFrom(other);
914 }
915
916 SmallDenseMap(SmallDenseMap &&other) : BaseT() {
917 init(0);
918 swap(other);
919 }
920
921 template<typename InputIt>
922 SmallDenseMap(const InputIt &I, const InputIt &E) {
923 init(NextPowerOf2(std::distance(I, E)));
924 this->insert(I, E);
925 }
926
927 SmallDenseMap(std::initializer_list<typename BaseT::value_type> Vals)
928 : SmallDenseMap(Vals.begin(), Vals.end()) {}
929
930 ~SmallDenseMap() {
931 this->destroyAll();
932 deallocateBuckets();
933 }
934
935 void swap(SmallDenseMap& RHS) {
936 unsigned TmpNumEntries = RHS.NumEntries;
937 RHS.NumEntries = NumEntries;
938 NumEntries = TmpNumEntries;
939 std::swap(NumTombstones, RHS.NumTombstones);
940
941 const KeyT EmptyKey = this->getEmptyKey();
942 const KeyT TombstoneKey = this->getTombstoneKey();
943 if (Small && RHS.Small) {
944 // If we're swapping inline bucket arrays, we have to cope with some of
945 // the tricky bits of DenseMap's storage system: the buckets are not
946 // fully initialized. Thus we swap every key, but we may have
947 // a one-directional move of the value.
948 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
949 BucketT *LHSB = &getInlineBuckets()[i],
950 *RHSB = &RHS.getInlineBuckets()[i];
951 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
952 !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
953 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
954 !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
955 if (hasLHSValue && hasRHSValue) {
956 // Swap together if we can...
957 std::swap(*LHSB, *RHSB);
958 continue;
959 }
960 // Swap separately and handle any asymmetry.
961 std::swap(LHSB->getFirst(), RHSB->getFirst());
962 if (hasLHSValue) {
963 ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
964 LHSB->getSecond().~ValueT();
965 } else if (hasRHSValue) {
966 ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
967 RHSB->getSecond().~ValueT();
968 }
969 }
970 return;
971 }
972 if (!Small && !RHS.Small) {
973 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
974 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
975 return;
976 }
977
978 SmallDenseMap &SmallSide = Small ? *this : RHS;
979 SmallDenseMap &LargeSide = Small ? RHS : *this;
980
981 // First stash the large side's rep and move the small side across.
982 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
983 LargeSide.getLargeRep()->~LargeRep();
984 LargeSide.Small = true;
985 // This is similar to the standard move-from-old-buckets, but the bucket
986 // count hasn't actually rotated in this case. So we have to carefully
987 // move construct the keys and values into their new locations, but there
988 // is no need to re-hash things.
989 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
990 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
991 *OldB = &SmallSide.getInlineBuckets()[i];
992 ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
993 OldB->getFirst().~KeyT();
994 if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
995 !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
996 ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
997 OldB->getSecond().~ValueT();
998 }
999 }
1000
1001 // The hard part of moving the small buckets across is done, just move
1002 // the TmpRep into its new home.
1003 SmallSide.Small = false;
1004 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
1005 }
1006
1007 SmallDenseMap& operator=(const SmallDenseMap& other) {
1008 if (&other != this)
1009 copyFrom(other);
1010 return *this;
1011 }
1012
1013 SmallDenseMap& operator=(SmallDenseMap &&other) {
1014 this->destroyAll();
1015 deallocateBuckets();
1016 init(0);
1017 swap(other);
1018 return *this;
1019 }
1020
1021 void copyFrom(const SmallDenseMap& other) {
1022 this->destroyAll();
1023 deallocateBuckets();
1024 Small = true;
1025 if (other.getNumBuckets() > InlineBuckets) {
1026 Small = false;
1027 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
1028 }
1029 this->BaseT::copyFrom(other);
1030 }
1031
1032 void init(unsigned InitBuckets) {
1033 Small = true;
1034 if (InitBuckets > InlineBuckets) {
1035 Small = false;
1036 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
1037 }
1038 this->BaseT::initEmpty();
1039 }
1040
1041 void grow(unsigned AtLeast) {
1042 if (AtLeast > InlineBuckets)
1043 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
1044
1045 if (Small) {
1046 // First move the inline buckets into a temporary storage.
1047 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
1048 BucketT *TmpBegin = reinterpret_cast<BucketT *>(&TmpStorage);
1049 BucketT *TmpEnd = TmpBegin;
1050
1051 // Loop over the buckets, moving non-empty, non-tombstones into the
1052 // temporary storage. Have the loop move the TmpEnd forward as it goes.
1053 const KeyT EmptyKey = this->getEmptyKey();
1054 const KeyT TombstoneKey = this->getTombstoneKey();
1055 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
1056 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
1057 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
1058 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&((void)0)
1059 "Too many inline buckets!")((void)0);
1060 ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
1061 ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
1062 ++TmpEnd;
1063 P->getSecond().~ValueT();
1064 }
1065 P->getFirst().~KeyT();
1066 }
1067
1068 // AtLeast == InlineBuckets can happen if there are many tombstones,
1069 // and grow() is used to remove them. Usually we always switch to the
1070 // large rep here.
1071 if (AtLeast > InlineBuckets) {
1072 Small = false;
1073 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1074 }
1075 this->moveFromOldBuckets(TmpBegin, TmpEnd);
1076 return;
1077 }
1078
1079 LargeRep OldRep = std::move(*getLargeRep());
1080 getLargeRep()->~LargeRep();
1081 if (AtLeast <= InlineBuckets) {
1082 Small = true;
1083 } else {
1084 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1085 }
1086
1087 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
1088
1089 // Free the old table.
1090 deallocate_buffer(OldRep.Buckets, sizeof(BucketT) * OldRep.NumBuckets,
1091 alignof(BucketT));
1092 }
1093
1094 void shrink_and_clear() {
1095 unsigned OldSize = this->size();
1096 this->destroyAll();
1097
1098 // Reduce the number of buckets.
1099 unsigned NewNumBuckets = 0;
1100 if (OldSize) {
1101 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
1102 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
1103 NewNumBuckets = 64;
1104 }
1105 if ((Small && NewNumBuckets <= InlineBuckets) ||
1106 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
1107 this->BaseT::initEmpty();
1108 return;
1109 }
1110
1111 deallocateBuckets();
1112 init(NewNumBuckets);
1113 }
1114
1115private:
1116 unsigned getNumEntries() const {
1117 return NumEntries;
1118 }
1119
1120 void setNumEntries(unsigned Num) {
1121 // NumEntries is hardcoded to be 31 bits wide.
1122 assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries")((void)0);
1123 NumEntries = Num;
1124 }
1125
1126 unsigned getNumTombstones() const {
1127 return NumTombstones;
1128 }
1129
1130 void setNumTombstones(unsigned Num) {
1131 NumTombstones = Num;
1132 }
1133
1134 const BucketT *getInlineBuckets() const {
1135 assert(Small)((void)0);
1136 // Note that this cast does not violate aliasing rules as we assert that
1137 // the memory's dynamic type is the small, inline bucket buffer, and the
1138 // 'storage' is a POD containing a char buffer.
1139 return reinterpret_cast<const BucketT *>(&storage);
1140 }
1141
1142 BucketT *getInlineBuckets() {
1143 return const_cast<BucketT *>(
1144 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
1145 }
1146
1147 const LargeRep *getLargeRep() const {
1148 assert(!Small)((void)0);
1149 // Note, same rule about aliasing as with getInlineBuckets.
1150 return reinterpret_cast<const LargeRep *>(&storage);
1151 }
1152
1153 LargeRep *getLargeRep() {
1154 return const_cast<LargeRep *>(
1155 const_cast<const SmallDenseMap *>(this)->getLargeRep());
1156 }
1157
1158 const BucketT *getBuckets() const {
1159 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
1160 }
1161
1162 BucketT *getBuckets() {
1163 return const_cast<BucketT *>(
1164 const_cast<const SmallDenseMap *>(this)->getBuckets());
1165 }
1166
1167 unsigned getNumBuckets() const {
1168 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
1169 }
1170
1171 void deallocateBuckets() {
1172 if (Small)
1173 return;
1174
1175 deallocate_buffer(getLargeRep()->Buckets,
1176 sizeof(BucketT) * getLargeRep()->NumBuckets,
1177 alignof(BucketT));
1178 getLargeRep()->~LargeRep();
1179 }
1180
1181 LargeRep allocateBuckets(unsigned Num) {
1182 assert(Num > InlineBuckets && "Must allocate more buckets than are inline")((void)0);
1183 LargeRep Rep = {static_cast<BucketT *>(allocate_buffer(
1184 sizeof(BucketT) * Num, alignof(BucketT))),
1185 Num};
1186 return Rep;
1187 }
1188};
1189
1190template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
1191 bool IsConst>
1192class DenseMapIterator : DebugEpochBase::HandleBase {
1193 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1194 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
1195
1196public:
1197 using difference_type = ptrdiff_t;
1198 using value_type =
1199 typename std::conditional<IsConst, const Bucket, Bucket>::type;
1200 using pointer = value_type *;
1201 using reference = value_type &;
1202 using iterator_category = std::forward_iterator_tag;
1203
1204private:
1205 pointer Ptr = nullptr;
1206 pointer End = nullptr;
1207
1208public:
1209 DenseMapIterator() = default;
1210
1211 DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
1212 bool NoAdvance = false)
1213 : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1214 assert(isHandleInSync() && "invalid construction!")((void)0);
1215
1216 if (NoAdvance) return;
1217 if (shouldReverseIterate<KeyT>()) {
1218 RetreatPastEmptyBuckets();
1219 return;
1220 }
1221 AdvancePastEmptyBuckets();
1222 }
1223
1224 // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1225 // for const iterator destinations so it doesn't end up as a user defined copy
1226 // constructor.
1227 template <bool IsConstSrc,
1228 typename = std::enable_if_t<!IsConstSrc && IsConst>>
1229 DenseMapIterator(
1230 const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
1231 : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1232
1233 reference operator*() const {
1234 assert(isHandleInSync() && "invalid iterator access!")((void)0);
1235 assert(Ptr != End && "dereferencing end() iterator")((void)0);
1236 if (shouldReverseIterate<KeyT>())
1237 return Ptr[-1];
1238 return *Ptr;
1239 }
1240 pointer operator->() const {
1241 assert(isHandleInSync() && "invalid iterator access!")((void)0);
1242 assert(Ptr != End && "dereferencing end() iterator")((void)0);
1243 if (shouldReverseIterate<KeyT>())
1244 return &(Ptr[-1]);
1245 return Ptr;
1246 }
1247
1248 friend bool operator==(const DenseMapIterator &LHS,
1249 const DenseMapIterator &RHS) {
1250 assert((!LHS.Ptr || LHS.isHandleInSync()) && "handle not in sync!")((void)0);
1251 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!")((void)0);
1252 assert(LHS.getEpochAddress() == RHS.getEpochAddress() &&((void)0)
1253 "comparing incomparable iterators!")((void)0);
1254 return LHS.Ptr == RHS.Ptr;
27
Assuming 'LHS.Ptr' is not equal to 'RHS.Ptr'
28
Returning zero, which participates in a condition later
1255 }
1256
1257 friend bool operator!=(const DenseMapIterator &LHS,
1258 const DenseMapIterator &RHS) {
1259 return !(LHS == RHS);
26
Calling 'operator=='
29
Returning from 'operator=='
30
Returning the value 1, which participates in a condition later
1260 }
1261
1262 inline DenseMapIterator& operator++() { // Preincrement
1263 assert(isHandleInSync() && "invalid iterator access!")((void)0);
1264 assert(Ptr != End && "incrementing end() iterator")((void)0);
1265 if (shouldReverseIterate<KeyT>()) {
1266 --Ptr;
1267 RetreatPastEmptyBuckets();
1268 return *this;
1269 }
1270 ++Ptr;
1271 AdvancePastEmptyBuckets();
1272 return *this;
1273 }
1274 DenseMapIterator operator++(int) { // Postincrement
1275 assert(isHandleInSync() && "invalid iterator access!")((void)0);
1276 DenseMapIterator tmp = *this; ++*this; return tmp;
1277 }
1278
1279private:
1280 void AdvancePastEmptyBuckets() {
1281 assert(Ptr <= End)((void)0);
1282 const KeyT Empty = KeyInfoT::getEmptyKey();
1283 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1284
1285 while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1286 KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1287 ++Ptr;
1288 }
1289
1290 void RetreatPastEmptyBuckets() {
1291 assert(Ptr >= End)((void)0);
1292 const KeyT Empty = KeyInfoT::getEmptyKey();
1293 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1294
1295 while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
1296 KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
1297 --Ptr;
1298 }
1299};
1300
1301template <typename KeyT, typename ValueT, typename KeyInfoT>
1302inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1303 return X.getMemorySize();
1304}
1305
1306} // end namespace llvm
1307
1308#endif // LLVM_ADT_DENSEMAP_H