1 //===-------------- ARM64CollectLOH.cpp - ARM64 collect LOH pass --*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that collect the Linker Optimization Hint (LOH).
11 // This pass should be run at the very end of the compilation flow, just before
13 // To be useful for the linker, the LOH must be printed into the assembly file.
15 // A LOH describes a sequence of instructions that may be optimized by the
17 // This same sequence cannot be optimized by the compiler because some of
18 // the information will be known at link time.
19 // For instance, consider the following sequence:
20 // L1: adrp xA, sym@PAGE
21 // L2: add xB, xA, sym@PAGEOFF
22 // L3: ldr xC, [xB, #imm]
23 // This sequence can be turned into:
24 // A literal load if sym@PAGE + sym@PAGEOFF + #imm - address(L3) is < 1MB:
25 // L3: ldr xC, sym+#imm
26 // It may also be turned into either the following more efficient
28 // - If sym@PAGEOFF + #imm fits the encoding space of L3.
29 // L1: adrp xA, sym@PAGE
30 // L3: ldr xC, [xB, sym@PAGEOFF + #imm]
31 // - If sym@PAGE + sym@PAGEOFF - address(L1) < 1MB:
33 // L3: ldr xC, [xB, #imm]
35 // To be valid a LOH must meet all the requirements needed by all the related
36 // possible linker transformations.
37 // For instance, using the running example, the constraints to emit
38 // ".loh AdrpAddLdr" are:
39 // - L1, L2, and L3 instructions are of the expected type, i.e.,
40 // respectively ADRP, ADD (immediate), and LD.
41 // - The result of L1 is used only by L2.
42 // - The register argument (xA) used in the ADD instruction is defined
44 // - The result of L2 is used only by L3.
45 // - The base address (xB) in L3 is defined only L2.
46 // - The ADRP in L1 and the ADD in L2 must reference the same symbol using
47 // @PAGE/@PAGEOFF with no additional constants
49 // Currently supported LOHs are:
50 // * So called non-ADRP-related:
51 // - .loh AdrpAddLdr L1, L2, L3:
52 // L1: adrp xA, sym@PAGE
53 // L2: add xB, xA, sym@PAGEOFF
54 // L3: ldr xC, [xB, #imm]
55 // - .loh AdrpLdrGotLdr L1, L2, L3:
56 // L1: adrp xA, sym@GOTPAGE
57 // L2: ldr xB, [xA, sym@GOTPAGEOFF]
58 // L3: ldr xC, [xB, #imm]
59 // - .loh AdrpLdr L1, L3:
60 // L1: adrp xA, sym@PAGE
61 // L3: ldr xC, [xA, sym@PAGEOFF]
62 // - .loh AdrpAddStr L1, L2, L3:
63 // L1: adrp xA, sym@PAGE
64 // L2: add xB, xA, sym@PAGEOFF
65 // L3: str xC, [xB, #imm]
66 // - .loh AdrpLdrGotStr L1, L2, L3:
67 // L1: adrp xA, sym@GOTPAGE
68 // L2: ldr xB, [xA, sym@GOTPAGEOFF]
69 // L3: str xC, [xB, #imm]
70 // - .loh AdrpAdd L1, L2:
71 // L1: adrp xA, sym@PAGE
72 // L2: add xB, xA, sym@PAGEOFF
73 // For all these LOHs, L1, L2, L3 form a simple chain:
74 // L1 result is used only by L2 and L2 result by L3.
75 // L3 LOH-related argument is defined only by L2 and L2 LOH-related argument
77 // All these LOHs aim at using more efficient load/store patterns by folding
78 // some instructions used to compute the address directly into the load/store.
80 // * So called ADRP-related:
81 // - .loh AdrpAdrp L2, L1:
82 // L2: ADRP xA, sym1@PAGE
83 // L1: ADRP xA, sym2@PAGE
84 // L2 dominates L1 and xA is not redifined between L2 and L1
85 // This LOH aims at getting rid of redundant ADRP instructions.
87 // The overall design for emitting the LOHs is:
88 // 1. ARM64CollectLOH (this pass) records the LOHs in the ARM64FunctionInfo.
89 // 2. ARM64AsmPrinter reads the LOHs from ARM64FunctionInfo and it:
90 // 1. Associates them a label.
91 // 2. Emits them in a MCStreamer (EmitLOHDirective).
92 // - The MCMachOStreamer records them into the MCAssembler.
93 // - The MCAsmStreamer prints them.
94 // - Other MCStreamers ignore them.
95 // 3. Closes the MCStreamer:
96 // - The MachObjectWriter gets them from the MCAssembler and writes
97 // them in the object file.
98 // - Other ObjectWriters ignore them.
99 //===----------------------------------------------------------------------===//
101 #define DEBUG_TYPE "arm64-collect-loh"
103 #include "ARM64InstrInfo.h"
104 #include "ARM64MachineFunctionInfo.h"
105 #include "MCTargetDesc/ARM64AddressingModes.h"
106 #include "llvm/ADT/BitVector.h"
107 #include "llvm/ADT/DenseMap.h"
108 #include "llvm/ADT/MapVector.h"
109 #include "llvm/ADT/SetVector.h"
110 #include "llvm/ADT/SmallVector.h"
111 #include "llvm/CodeGen/MachineBasicBlock.h"
112 #include "llvm/CodeGen/MachineDominators.h"
113 #include "llvm/CodeGen/MachineFunctionPass.h"
114 #include "llvm/CodeGen/MachineInstr.h"
115 #include "llvm/CodeGen/MachineInstrBuilder.h"
116 #include "llvm/Target/TargetInstrInfo.h"
117 #include "llvm/Target/TargetMachine.h"
118 #include "llvm/Target/TargetRegisterInfo.h"
119 #include "llvm/Support/CommandLine.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include "llvm/ADT/Statistic.h"
124 using namespace llvm;
127 PreCollectRegister("arm64-collect-loh-pre-collect-register", cl::Hidden,
128 cl::desc("Restrict analysis to registers invovled"
133 BasicBlockScopeOnly("arm64-collect-loh-bb-only", cl::Hidden,
134 cl::desc("Restrict analysis at basic block scope"),
137 STATISTIC(NumADRPSimpleCandidate,
138 "Number of simplifiable ADRP dominate by another");
139 STATISTIC(NumADRPComplexCandidate2,
140 "Number of simplifiable ADRP reachable by 2 defs");
141 STATISTIC(NumADRPComplexCandidate3,
142 "Number of simplifiable ADRP reachable by 3 defs");
143 STATISTIC(NumADRPComplexCandidateOther,
144 "Number of simplifiable ADRP reachable by 4 or more defs");
145 STATISTIC(NumADDToSTRWithImm,
146 "Number of simplifiable STR with imm reachable by ADD");
147 STATISTIC(NumLDRToSTRWithImm,
148 "Number of simplifiable STR with imm reachable by LDR");
149 STATISTIC(NumADDToSTR, "Number of simplifiable STR reachable by ADD");
150 STATISTIC(NumLDRToSTR, "Number of simplifiable STR reachable by LDR");
151 STATISTIC(NumADDToLDRWithImm,
152 "Number of simplifiable LDR with imm reachable by ADD");
153 STATISTIC(NumLDRToLDRWithImm,
154 "Number of simplifiable LDR with imm reachable by LDR");
155 STATISTIC(NumADDToLDR, "Number of simplifiable LDR reachable by ADD");
156 STATISTIC(NumLDRToLDR, "Number of simplifiable LDR reachable by LDR");
157 STATISTIC(NumADRPToLDR, "Number of simplifiable LDR reachable by ADRP");
158 STATISTIC(NumCplxLvl1, "Number of complex case of level 1");
159 STATISTIC(NumTooCplxLvl1, "Number of too complex case of level 1");
160 STATISTIC(NumCplxLvl2, "Number of complex case of level 2");
161 STATISTIC(NumTooCplxLvl2, "Number of too complex case of level 2");
162 STATISTIC(NumADRSimpleCandidate, "Number of simplifiable ADRP + ADD");
163 STATISTIC(NumADRComplexCandidate, "Number of too complex ADRP + ADD");
166 void initializeARM64CollectLOHPass(PassRegistry &);
170 struct ARM64CollectLOH : public MachineFunctionPass {
172 ARM64CollectLOH() : MachineFunctionPass(ID) {
173 initializeARM64CollectLOHPass(*PassRegistry::getPassRegistry());
176 virtual bool runOnMachineFunction(MachineFunction &MF);
178 virtual const char *getPassName() const {
179 return "ARM64 Collect Linker Optimization Hint (LOH)";
182 void getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesAll();
184 MachineFunctionPass::getAnalysisUsage(AU);
185 AU.addRequired<MachineDominatorTree>();
191 /// A set of MachineInstruction.
192 typedef SetVector<const MachineInstr *> SetOfMachineInstr;
193 /// Map a basic block to a set of instructions per register.
194 /// This is used to represent the exposed uses of a basic block
196 typedef MapVector<const MachineBasicBlock *, SetOfMachineInstr *>
197 BlockToSetOfInstrsPerColor;
198 /// Map a basic block to an instruction per register.
199 /// This is used to represent the live-out definitions of a basic block
201 typedef MapVector<const MachineBasicBlock *, const MachineInstr **>
202 BlockToInstrPerColor;
203 /// Map an instruction to a set of instructions. Used to represent the
204 /// mapping def to reachable uses or use to definitions.
205 typedef MapVector<const MachineInstr *, SetOfMachineInstr> InstrToInstrs;
206 /// Map a basic block to a BitVector.
207 /// This is used to record the kill registers per basic block.
208 typedef MapVector<const MachineBasicBlock *, BitVector> BlockToRegSet;
210 /// Map a register to a dense id.
211 typedef DenseMap<unsigned, unsigned> MapRegToId;
212 /// Map a dense id to a register. Used for debug purposes.
213 typedef SmallVector<unsigned, 32> MapIdToReg;
214 } // end anonymous namespace.
216 char ARM64CollectLOH::ID = 0;
218 INITIALIZE_PASS_BEGIN(ARM64CollectLOH, "arm64-collect-loh",
219 "ARM64 Collect Linker Optimization Hint (LOH)", false,
221 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
222 INITIALIZE_PASS_END(ARM64CollectLOH, "arm64-collect-loh",
223 "ARM64 Collect Linker Optimization Hint (LOH)", false,
226 /// Given a couple (MBB, reg) get the corresponding set of instruction from
227 /// the given "sets".
228 /// If this couple does not reference any set, an empty set is added to "sets"
229 /// for this couple and returned.
230 /// \param nbRegs is used internally allocate some memory. It must be consistent
231 /// with the way sets is used.
232 static SetOfMachineInstr &getSet(BlockToSetOfInstrsPerColor &sets,
233 const MachineBasicBlock &MBB, unsigned reg,
235 SetOfMachineInstr *result;
236 BlockToSetOfInstrsPerColor::iterator it = sets.find(&MBB);
237 if (it != sets.end())
240 result = sets[&MBB] = new SetOfMachineInstr[nbRegs];
245 /// Given a couple (reg, MI) get the corresponding set of instructions from the
246 /// the given "sets".
247 /// This is used to get the uses record in sets of a definition identified by
248 /// MI and reg, i.e., MI defines reg.
249 /// If the couple does not reference anything, an empty set is added to
251 /// \pre set[reg] is valid.
252 static SetOfMachineInstr &getUses(InstrToInstrs *sets, unsigned reg,
253 const MachineInstr &MI) {
254 return sets[reg][&MI];
257 /// Same as getUses but does not modify the input map: sets.
258 /// \return NULL if the couple (reg, MI) is not in sets.
259 static const SetOfMachineInstr *getUses(const InstrToInstrs *sets, unsigned reg,
260 const MachineInstr &MI) {
261 InstrToInstrs::const_iterator Res = sets[reg].find(&MI);
262 if (Res != sets[reg].end())
263 return &(Res->second);
267 /// Initialize the reaching definition algorithm:
268 /// For each basic block BB in MF, record:
270 /// - its reachable uses (uses that are exposed to BB's predecessors).
271 /// - its the generated definitions.
272 /// \param DummyOp if not NULL, specifies a Dummy Operation to be added to
273 /// the list of uses of exposed defintions.
274 /// \param ADRPMode specifies to only consider ADRP instructions for generated
275 /// definition. It also consider definitions of ADRP instructions as uses and
276 /// ignore other uses. The ADRPMode is used to collect the information for LHO
277 /// that involve ADRP operation only.
278 static void initReachingDef(MachineFunction &MF,
279 InstrToInstrs *ColorOpToReachedUses,
280 BlockToInstrPerColor &Gen, BlockToRegSet &Kill,
281 BlockToSetOfInstrsPerColor &ReachableUses,
282 const MapRegToId &RegToId,
283 const MachineInstr *DummyOp, bool ADRPMode) {
284 const TargetMachine &TM = MF.getTarget();
285 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
287 unsigned NbReg = RegToId.size();
289 for (MachineBasicBlock &MBB : MF) {
290 const MachineInstr **&BBGen = Gen[&MBB];
291 BBGen = new const MachineInstr *[NbReg];
292 memset(BBGen, 0, sizeof(const MachineInstr *) * NbReg);
294 BitVector &BBKillSet = Kill[&MBB];
295 BBKillSet.resize(NbReg);
296 for (const MachineInstr &MI : MBB) {
297 bool IsADRP = MI.getOpcode() == ARM64::ADRP;
299 // Process uses first.
300 if (IsADRP || !ADRPMode)
301 for (const MachineOperand &MO : MI.operands()) {
302 // Treat ADRP def as use, as the goal of the analysis is to find
303 // ADRP defs reached by other ADRP defs.
304 if (!MO.isReg() || (!ADRPMode && !MO.isUse()) ||
305 (ADRPMode && (!IsADRP || !MO.isDef())))
307 unsigned CurReg = MO.getReg();
308 MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
309 if (ItCurRegId == RegToId.end())
311 CurReg = ItCurRegId->second;
313 // if CurReg has not been defined, this use is reachable.
314 if (!BBGen[CurReg] && !BBKillSet.test(CurReg))
315 getSet(ReachableUses, MBB, CurReg, NbReg).insert(&MI);
316 // current basic block definition for this color, if any, is in Gen.
318 getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(&MI);
322 for (const MachineOperand &MO : MI.operands()) {
325 // Clobbers kill the related colors.
326 const uint32_t *PreservedRegs = MO.getRegMask();
328 // Set generated regs.
329 for (const auto Entry : RegToId) {
330 unsigned Reg = Entry.second;
331 // Use the global register ID when querying APIs external to this
333 if (MachineOperand::clobbersPhysReg(PreservedRegs, Entry.first)) {
334 // Do not register clobbered definition for no ADRP.
335 // This definition is not used anyway (otherwise register
336 // allocation is wrong).
337 BBGen[Reg] = ADRPMode ? &MI : NULL;
343 // Process register defs.
344 for (const MachineOperand &MO : MI.operands()) {
345 if (!MO.isReg() || !MO.isDef())
347 unsigned CurReg = MO.getReg();
348 MapRegToId::const_iterator ItCurRegId = RegToId.find(CurReg);
349 if (ItCurRegId == RegToId.end())
352 for (MCRegAliasIterator AI(CurReg, TRI, true); AI.isValid(); ++AI) {
353 MapRegToId::const_iterator ItRegId = RegToId.find(*AI);
354 assert(ItRegId != RegToId.end() &&
355 "Sub-register of an "
356 "involved register, not recorded as involved!");
357 BBKillSet.set(ItRegId->second);
358 BBGen[ItRegId->second] = &MI;
360 BBGen[ItCurRegId->second] = &MI;
364 // If we restrict our analysis to basic block scope, conservatively add a
366 // use for each generated value.
367 if (!ADRPMode && DummyOp && !MBB.succ_empty())
368 for (unsigned CurReg = 0; CurReg < NbReg; ++CurReg)
370 getUses(ColorOpToReachedUses, CurReg, *BBGen[CurReg]).insert(DummyOp);
374 /// Reaching def core algorithm:
375 /// while an Out has changed
378 /// In[bb][color] = U Out[bb.predecessors][color]
379 /// insert reachableUses[bb][color] in each in[bb][color]
382 /// Out[bb] = Gen[bb] U (In[bb] - Kill[bb])
383 static void reachingDefAlgorithm(MachineFunction &MF,
384 InstrToInstrs *ColorOpToReachedUses,
385 BlockToSetOfInstrsPerColor &In,
386 BlockToSetOfInstrsPerColor &Out,
387 BlockToInstrPerColor &Gen, BlockToRegSet &Kill,
388 BlockToSetOfInstrsPerColor &ReachableUses,
393 for (MachineBasicBlock &MBB : MF) {
395 for (CurReg = 0; CurReg < NbReg; ++CurReg) {
396 SetOfMachineInstr &BBInSet = getSet(In, MBB, CurReg, NbReg);
397 SetOfMachineInstr &BBReachableUses =
398 getSet(ReachableUses, MBB, CurReg, NbReg);
399 SetOfMachineInstr &BBOutSet = getSet(Out, MBB, CurReg, NbReg);
400 unsigned Size = BBOutSet.size();
401 // In[bb][color] = U Out[bb.predecessors][color]
402 for (MachineBasicBlock *PredMBB : MBB.predecessors()) {
403 SetOfMachineInstr &PredOutSet = getSet(Out, *PredMBB, CurReg, NbReg);
404 BBInSet.insert(PredOutSet.begin(), PredOutSet.end());
406 // insert reachableUses[bb][color] in each in[bb][color] op.reachedses
407 for (const MachineInstr *MI : BBInSet) {
408 SetOfMachineInstr &OpReachedUses =
409 getUses(ColorOpToReachedUses, CurReg, *MI);
410 OpReachedUses.insert(BBReachableUses.begin(), BBReachableUses.end());
412 // Out[bb] = Gen[bb] U (In[bb] - Kill[bb])
413 if (!Kill[&MBB].test(CurReg))
414 BBOutSet.insert(BBInSet.begin(), BBInSet.end());
415 if (Gen[&MBB][CurReg])
416 BBOutSet.insert(Gen[&MBB][CurReg]);
417 HasChanged |= BBOutSet.size() != Size;
420 } while (HasChanged);
423 /// Release all memory dynamically allocated during the reaching
424 /// definition algorithm.
425 static void finitReachingDef(BlockToSetOfInstrsPerColor &In,
426 BlockToSetOfInstrsPerColor &Out,
427 BlockToInstrPerColor &Gen,
428 BlockToSetOfInstrsPerColor &ReachableUses) {
433 for (auto &IT : ReachableUses)
439 /// Reaching definition algorithm.
440 /// \param MF function on which the algorithm will operate.
441 /// \param[out] ColorOpToReachedUses will contain the result of the reaching
443 /// \param ADRPMode specify whether the reaching def algorithm should be tuned
444 /// for ADRP optimization. \see initReachingDef for more details.
445 /// \param DummyOp if not NULL, the algorithm will work at
446 /// basic block scope and will set for every exposed definition a use to
448 /// \pre ColorOpToReachedUses is an array of at least number of registers of
450 static void reachingDef(MachineFunction &MF,
451 InstrToInstrs *ColorOpToReachedUses,
452 const MapRegToId &RegToId, bool ADRPMode = false,
453 const MachineInstr *DummyOp = NULL) {
455 // For each basic block.
456 // Out: a set per color of definitions that reach the
457 // out boundary of this block.
458 // In: Same as Out but for in boundary.
459 // Gen: generated color in this block (one operation per color).
460 // Kill: register set of killed color in this block.
461 // ReachableUses: a set per color of uses (operation) reachable
462 // for "In" definitions.
463 BlockToSetOfInstrsPerColor Out, In, ReachableUses;
464 BlockToInstrPerColor Gen;
467 // Initialize Gen, kill and reachableUses.
468 initReachingDef(MF, ColorOpToReachedUses, Gen, Kill, ReachableUses, RegToId,
473 reachingDefAlgorithm(MF, ColorOpToReachedUses, In, Out, Gen, Kill,
474 ReachableUses, RegToId.size());
477 finitReachingDef(In, Out, Gen, ReachableUses);
481 /// print the result of the reaching definition algorithm.
482 static void printReachingDef(const InstrToInstrs *ColorOpToReachedUses,
483 unsigned NbReg, const TargetRegisterInfo *TRI,
484 const MapIdToReg &IdToReg) {
486 for (CurReg = 0; CurReg < NbReg; ++CurReg) {
487 if (ColorOpToReachedUses[CurReg].empty())
489 DEBUG(dbgs() << "*** Reg " << PrintReg(IdToReg[CurReg], TRI) << " ***\n");
491 for (const auto &DefsIt : ColorOpToReachedUses[CurReg]) {
492 DEBUG(dbgs() << "Def:\n");
493 DEBUG(DefsIt.first->print(dbgs()));
494 DEBUG(dbgs() << "Reachable uses:\n");
495 for (const MachineInstr *MI : DefsIt.second)
496 DEBUG(MI->print(dbgs()));
502 /// Answer the following question: Can Def be one of the definition
503 /// involved in a part of a LOH?
504 static bool canDefBePartOfLOH(const MachineInstr *Def) {
505 unsigned Opc = Def->getOpcode();
506 // Accept ADRP, ADDLow and LOADGot.
513 // Check immediate to see if the immediate is an address.
514 switch (Def->getOperand(2).getType()) {
517 case MachineOperand::MO_GlobalAddress:
518 case MachineOperand::MO_JumpTableIndex:
519 case MachineOperand::MO_ConstantPoolIndex:
520 case MachineOperand::MO_BlockAddress:
524 // Check immediate to see if the immediate is an address.
525 switch (Def->getOperand(2).getType()) {
528 case MachineOperand::MO_GlobalAddress:
536 /// Check whether the given instruction can the end of a LOH chain involving a
538 static bool isCandidateStore(const MachineInstr *Instr) {
539 switch (Instr->getOpcode()) {
549 // In case we have str xA, [xA, #imm], this is two different uses
550 // of xA and we cannot fold, otherwise the xA stored may be wrong,
551 // even if #imm == 0.
552 if (Instr->getOperand(0).getReg() != Instr->getOperand(1).getReg())
558 /// Given the result of a reaching definition algorithm in ColorOpToReachedUses,
559 /// Build the Use to Defs information and filter out obvious non-LOH candidates.
560 /// In ADRPMode, non-LOH candidates are "uses" with non-ADRP definitions.
561 /// In non-ADRPMode, non-LOH candidates are "uses" with several definition,
562 /// i.e., no simple chain.
563 /// \param ADRPMode -- \see initReachingDef.
564 static void reachedUsesToDefs(InstrToInstrs &UseToReachingDefs,
565 const InstrToInstrs *ColorOpToReachedUses,
566 const MapRegToId &RegToId,
567 bool ADRPMode = false) {
569 SetOfMachineInstr NotCandidate;
570 unsigned NbReg = RegToId.size();
571 MapRegToId::const_iterator EndIt = RegToId.end();
572 for (unsigned CurReg = 0; CurReg < NbReg; ++CurReg) {
573 // If this color is never defined, continue.
574 if (ColorOpToReachedUses[CurReg].empty())
577 for (const auto &DefsIt : ColorOpToReachedUses[CurReg]) {
578 for (const MachineInstr *MI : DefsIt.second) {
579 const MachineInstr *Def = DefsIt.first;
580 MapRegToId::const_iterator It;
581 // if all the reaching defs are not adrp, this use will not be
583 if ((ADRPMode && Def->getOpcode() != ARM64::ADRP) ||
584 (!ADRPMode && !canDefBePartOfLOH(Def)) ||
585 (!ADRPMode && isCandidateStore(MI) &&
586 // store are LOH candidate iff the end of the chain is used as
588 ((It = RegToId.find((MI)->getOperand(1).getReg())) == EndIt ||
589 It->second != CurReg))) {
590 NotCandidate.insert(MI);
593 // Do not consider self reaching as a simplifiable case for ADRP.
594 if (!ADRPMode || MI != DefsIt.first) {
595 UseToReachingDefs[MI].insert(DefsIt.first);
596 // If UsesIt has several reaching definitions, it is not
597 // candidate for simplificaton in non-ADRPMode.
598 if (!ADRPMode && UseToReachingDefs[MI].size() > 1)
599 NotCandidate.insert(MI);
604 for (const MachineInstr *Elem : NotCandidate) {
605 DEBUG(dbgs() << "Too many reaching defs: " << *Elem << "\n");
606 // It would have been better if we could just remove the entry
607 // from the map. Because of that, we have to filter the garbage
608 // (second.empty) in the subsequence analysis.
609 UseToReachingDefs[Elem].clear();
613 /// Based on the use to defs information (in ADRPMode), compute the
614 /// opportunities of LOH ADRP-related.
615 static void computeADRP(const InstrToInstrs &UseToDefs,
616 ARM64FunctionInfo &ARM64FI,
617 const MachineDominatorTree *MDT) {
618 DEBUG(dbgs() << "*** Compute LOH for ADRP\n");
619 for (const auto &Entry : UseToDefs) {
620 unsigned Size = Entry.second.size();
624 const MachineInstr *L2 = *Entry.second.begin();
625 const MachineInstr *L1 = Entry.first;
626 if (!MDT->dominates(L2, L1)) {
627 DEBUG(dbgs() << "Dominance check failed:\n" << *L2 << '\n' << *L1
631 DEBUG(dbgs() << "Record AdrpAdrp:\n" << *L2 << '\n' << *L1 << '\n');
632 SmallVector<const MachineInstr *, 2> Args;
635 ARM64FI.addLOHDirective(MCLOH_AdrpAdrp, Args);
636 ++NumADRPSimpleCandidate;
640 ++NumADRPComplexCandidate2;
642 ++NumADRPComplexCandidate3;
644 ++NumADRPComplexCandidateOther;
646 // if Size < 1, the use should have been removed from the candidates
647 assert(Size >= 1 && "No reaching defs for that use!");
651 /// Check whether the given instruction can be the end of a LOH chain
652 /// involving a load.
653 static bool isCandidateLoad(const MachineInstr *Instr) {
654 switch (Instr->getOpcode()) {
657 case ARM64::LDRSBWui:
658 case ARM64::LDRSBXui:
659 case ARM64::LDRSHWui:
660 case ARM64::LDRSHXui:
669 if (Instr->getOperand(2).getTargetFlags() & ARM64II::MO_GOT)
677 /// Check whether the given instruction can load a litteral.
678 static bool supportLoadFromLiteral(const MachineInstr *Instr) {
679 switch (Instr->getOpcode()) {
694 /// Check whether the given instruction is a LOH candidate.
695 /// \param UseToDefs is used to check that Instr is at the end of LOH supported
697 /// \pre UseToDefs contains only on def per use, i.e., obvious non candidate are
698 /// already been filtered out.
699 static bool isCandidate(const MachineInstr *Instr,
700 const InstrToInstrs &UseToDefs,
701 const MachineDominatorTree *MDT) {
702 if (!isCandidateLoad(Instr) && !isCandidateStore(Instr))
705 const MachineInstr *Def = *UseToDefs.find(Instr)->second.begin();
706 if (Def->getOpcode() != ARM64::ADRP) {
707 // At this point, Def is ADDXri or LDRXui of the right type of
708 // symbol, because we filtered out the uses that were not defined
709 // by these kind of instructions (+ ADRP).
711 // Check if this forms a simple chain: each intermediate node must
712 // dominates the next one.
713 if (!MDT->dominates(Def, Instr))
715 // Move one node up in the simple chain.
716 if (UseToDefs.find(Def) ==
718 // The map may contain garbage we have to ignore.
720 UseToDefs.find(Def)->second.empty())
723 Def = *UseToDefs.find(Def)->second.begin();
725 // Check if we reached the top of the simple chain:
727 // - check the simple chain property: each intermediate node must
728 // dominates the next one.
729 if (Def->getOpcode() == ARM64::ADRP)
730 return MDT->dominates(Def, Instr);
734 static bool registerADRCandidate(const MachineInstr &Use,
735 const InstrToInstrs &UseToDefs,
736 const InstrToInstrs *DefsPerColorToUses,
737 ARM64FunctionInfo &ARM64FI,
738 SetOfMachineInstr *InvolvedInLOHs,
739 const MapRegToId &RegToId) {
740 // Look for opportunities to turn ADRP -> ADD or
741 // ADRP -> LDR GOTPAGEOFF into ADR.
742 // If ADRP has more than one use. Give up.
743 if (Use.getOpcode() != ARM64::ADDXri &&
744 (Use.getOpcode() != ARM64::LDRXui ||
745 !(Use.getOperand(2).getTargetFlags() & ARM64II::MO_GOT)))
747 InstrToInstrs::const_iterator It = UseToDefs.find(&Use);
748 // The map may contain garbage that we need to ignore.
749 if (It == UseToDefs.end() || It->second.empty())
751 const MachineInstr &Def = **It->second.begin();
752 if (Def.getOpcode() != ARM64::ADRP)
754 // Check the number of users of ADRP.
755 const SetOfMachineInstr *Users =
756 getUses(DefsPerColorToUses,
757 RegToId.find(Def.getOperand(0).getReg())->second, Def);
758 if (Users->size() > 1) {
759 ++NumADRComplexCandidate;
762 ++NumADRSimpleCandidate;
763 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(&Def)) &&
764 "ADRP already involved in LOH.");
765 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(&Use)) &&
766 "ADD already involved in LOH.");
767 DEBUG(dbgs() << "Record AdrpAdd\n" << Def << '\n' << Use << '\n');
769 SmallVector<const MachineInstr *, 2> Args;
770 Args.push_back(&Def);
771 Args.push_back(&Use);
773 ARM64FI.addLOHDirective(Use.getOpcode() == ARM64::ADDXri ? MCLOH_AdrpAdd
779 /// Based on the use to defs information (in non-ADRPMode), compute the
780 /// opportunities of LOH non-ADRP-related
781 static void computeOthers(const InstrToInstrs &UseToDefs,
782 const InstrToInstrs *DefsPerColorToUses,
783 ARM64FunctionInfo &ARM64FI, const MapRegToId &RegToId,
784 const MachineDominatorTree *MDT) {
785 SetOfMachineInstr *InvolvedInLOHs = NULL;
787 SetOfMachineInstr InvolvedInLOHsStorage;
788 InvolvedInLOHs = &InvolvedInLOHsStorage;
790 DEBUG(dbgs() << "*** Compute LOH for Others\n");
791 // ADRP -> ADD/LDR -> LDR/STR pattern.
792 // Fall back to ADRP -> ADD pattern if we fail to catch the bigger pattern.
794 // FIXME: When the statistics are not important,
795 // This initial filtering loop can be merged into the next loop.
796 // Currently, we didn't do it to have the same code for both DEBUG and
797 // NDEBUG builds. Indeed, the iterator of the second loop would need
799 SetOfMachineInstr PotentialCandidates;
800 SetOfMachineInstr PotentialADROpportunities;
801 for (auto &Use : UseToDefs) {
802 // If no definition is available, this is a non candidate.
803 if (Use.second.empty())
805 // Keep only instructions that are load or store and at the end of
806 // a ADRP -> ADD/LDR/Nothing chain.
807 // We already filtered out the no-chain cases.
808 if (!isCandidate(Use.first, UseToDefs, MDT)) {
809 PotentialADROpportunities.insert(Use.first);
812 PotentialCandidates.insert(Use.first);
815 // Make the following distinctions for statistics as the linker does
816 // know how to decode instructions:
817 // - ADD/LDR/Nothing make there different patterns.
818 // - LDR/STR make two different patterns.
819 // Hence, 6 - 1 base patterns.
820 // (because ADRP-> Nothing -> STR is not simplifiable)
822 // The linker is only able to have a simple semantic, i.e., if pattern A
824 // However, we want to see the opportunity we may miss if we were able to
825 // catch more complex cases.
827 // PotentialCandidates are result of a chain ADRP -> ADD/LDR ->
828 // A potential candidate becomes a candidate, if its current immediate
829 // operand is zero and all nodes of the chain have respectively only one user
831 SetOfMachineInstr DefsOfPotentialCandidates;
833 for (const MachineInstr *Candidate : PotentialCandidates) {
834 // Get the definition of the candidate i.e., ADD or LDR.
835 const MachineInstr *Def = *UseToDefs.find(Candidate)->second.begin();
836 // Record the elements of the chain.
837 const MachineInstr *L1 = Def;
838 const MachineInstr *L2 = NULL;
839 unsigned ImmediateDefOpc = Def->getOpcode();
840 if (Def->getOpcode() != ARM64::ADRP) {
841 // Check the number of users of this node.
842 const SetOfMachineInstr *Users =
843 getUses(DefsPerColorToUses,
844 RegToId.find(Def->getOperand(0).getReg())->second, *Def);
845 if (Users->size() > 1) {
847 // if all the uses of this def are in potential candidate, this is
848 // a complex candidate of level 2.
849 bool IsLevel2 = true;
850 for (const MachineInstr *MI : *Users) {
851 if (!PotentialCandidates.count(MI)) {
860 PotentialADROpportunities.insert(Def);
864 Def = *UseToDefs.find(Def)->second.begin();
866 } // else the element in the middle of the chain is nothing, thus
867 // Def already contains the first element of the chain.
869 // Check the number of users of the first node in the chain, i.e., ADRP
870 const SetOfMachineInstr *Users =
871 getUses(DefsPerColorToUses,
872 RegToId.find(Def->getOperand(0).getReg())->second, *Def);
873 if (Users->size() > 1) {
875 // if all the uses of this def are in the defs of the potential candidate,
876 // this is a complex candidate of level 1
877 if (DefsOfPotentialCandidates.empty()) {
879 DefsOfPotentialCandidates = PotentialCandidates;
880 for (const MachineInstr *Candidate : PotentialCandidates) {
881 if (!UseToDefs.find(Candidate)->second.empty())
882 DefsOfPotentialCandidates.insert(
883 *UseToDefs.find(Candidate)->second.begin());
887 for (auto &Use : *Users) {
888 if (!DefsOfPotentialCandidates.count(Use)) {
900 bool IsL2Add = (ImmediateDefOpc == ARM64::ADDXri);
901 // If the chain is three instructions long and ldr is the second element,
902 // then this ldr must load form GOT, otherwise this is not a correct chain.
903 if (L2 && !IsL2Add && L2->getOperand(2).getTargetFlags() != ARM64II::MO_GOT)
905 SmallVector<const MachineInstr *, 3> Args;
907 if (isCandidateLoad(Candidate)) {
909 // At this point, the candidate LOH indicates that the ldr instruction
910 // may use a direct access to the symbol. There is not such encoding
911 // for loads of byte and half.
912 if (!supportLoadFromLiteral(Candidate))
915 DEBUG(dbgs() << "Record AdrpLdr:\n" << *L1 << '\n' << *Candidate
917 Kind = MCLOH_AdrpLdr;
919 Args.push_back(Candidate);
920 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
921 "L1 already involved in LOH.");
922 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
923 "Candidate already involved in LOH.");
926 DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
927 << "Ldr:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
930 Kind = IsL2Add ? MCLOH_AdrpAddLdr : MCLOH_AdrpLdrGotLdr;
933 Args.push_back(Candidate);
935 PotentialADROpportunities.remove(L2);
936 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
937 "L1 already involved in LOH.");
938 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L2)) &&
939 "L2 already involved in LOH.");
940 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
941 "Candidate already involved in LOH.");
943 // get the immediate of the load
944 if (Candidate->getOperand(2).getImm() == 0)
945 if (ImmediateDefOpc == ARM64::ADDXri)
949 else if (ImmediateDefOpc == ARM64::ADDXri)
950 ++NumADDToLDRWithImm;
952 ++NumLDRToLDRWithImm;
956 if (ImmediateDefOpc == ARM64::ADRP)
960 DEBUG(dbgs() << "Record Adrp" << (IsL2Add ? "Add" : "LdrGot")
961 << "Str:\n" << *L1 << '\n' << *L2 << '\n' << *Candidate
964 Kind = IsL2Add ? MCLOH_AdrpAddStr : MCLOH_AdrpLdrGotStr;
967 Args.push_back(Candidate);
969 PotentialADROpportunities.remove(L2);
970 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L1)) &&
971 "L1 already involved in LOH.");
972 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(L2)) &&
973 "L2 already involved in LOH.");
974 assert((!InvolvedInLOHs || InvolvedInLOHs->insert(Candidate)) &&
975 "Candidate already involved in LOH.");
977 // get the immediate of the store
978 if (Candidate->getOperand(2).getImm() == 0)
979 if (ImmediateDefOpc == ARM64::ADDXri)
983 else if (ImmediateDefOpc == ARM64::ADDXri)
984 ++NumADDToSTRWithImm;
986 ++NumLDRToSTRWithImm;
990 ARM64FI.addLOHDirective(Kind, Args);
993 // Now, we grabbed all the big patterns, check ADR opportunities.
994 for (const MachineInstr *Candidate : PotentialADROpportunities)
995 registerADRCandidate(*Candidate, UseToDefs, DefsPerColorToUses, ARM64FI,
996 InvolvedInLOHs, RegToId);
999 /// Look for every register defined by potential LOHs candidates.
1000 /// Map these registers with dense id in @p RegToId and vice-versa in
1001 /// @p IdToReg. @p IdToReg is populated only in DEBUG mode.
1002 static void collectInvolvedReg(MachineFunction &MF, MapRegToId &RegToId,
1003 MapIdToReg &IdToReg,
1004 const TargetRegisterInfo *TRI) {
1005 unsigned CurRegId = 0;
1006 if (!PreCollectRegister) {
1007 unsigned NbReg = TRI->getNumRegs();
1008 for (; CurRegId < NbReg; ++CurRegId) {
1009 RegToId[CurRegId] = CurRegId;
1010 DEBUG(IdToReg.push_back(CurRegId));
1011 DEBUG(assert(IdToReg[CurRegId] == CurRegId && "Reg index mismatches"));
1016 DEBUG(dbgs() << "** Collect Involved Register\n");
1017 for (const auto &MBB : MF) {
1018 for (const MachineInstr &MI : MBB) {
1019 if (!canDefBePartOfLOH(&MI))
1023 for (MachineInstr::const_mop_iterator IO = MI.operands_begin(),
1024 IOEnd = MI.operands_end();
1025 IO != IOEnd; ++IO) {
1026 if (!IO->isReg() || !IO->isDef())
1028 unsigned CurReg = IO->getReg();
1029 for (MCRegAliasIterator AI(CurReg, TRI, true); AI.isValid(); ++AI)
1030 if (RegToId.find(*AI) == RegToId.end()) {
1031 DEBUG(IdToReg.push_back(*AI);
1032 assert(IdToReg[CurRegId] == *AI &&
1033 "Reg index mismatches insertion index."));
1034 RegToId[*AI] = CurRegId++;
1035 DEBUG(dbgs() << "Register: " << PrintReg(*AI, TRI) << '\n');
1042 bool ARM64CollectLOH::runOnMachineFunction(MachineFunction &MF) {
1043 const TargetMachine &TM = MF.getTarget();
1044 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1045 const MachineDominatorTree *MDT = &getAnalysis<MachineDominatorTree>();
1049 ARM64FunctionInfo *ARM64FI = MF.getInfo<ARM64FunctionInfo>();
1050 assert(ARM64FI && "No MachineFunctionInfo for this function!");
1052 DEBUG(dbgs() << "Looking for LOH in " << MF.getName() << '\n');
1054 collectInvolvedReg(MF, RegToId, IdToReg, TRI);
1055 if (RegToId.empty())
1058 MachineInstr *DummyOp = NULL;
1059 if (BasicBlockScopeOnly) {
1060 const ARM64InstrInfo *TII =
1061 static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
1062 // For local analysis, create a dummy operation to record uses that are not
1064 DummyOp = MF.CreateMachineInstr(TII->get(ARM64::COPY), DebugLoc());
1067 unsigned NbReg = RegToId.size();
1068 bool Modified = false;
1071 InstrToInstrs *ColorOpToReachedUses = new InstrToInstrs[NbReg];
1073 // Compute the reaching def in ADRP mode, meaning ADRP definitions
1074 // are first considered as uses.
1075 reachingDef(MF, ColorOpToReachedUses, RegToId, true, DummyOp);
1076 DEBUG(dbgs() << "ADRP reaching defs\n");
1077 DEBUG(printReachingDef(ColorOpToReachedUses, NbReg, TRI, IdToReg));
1079 // Translate the definition to uses map into a use to definitions map to ease
1080 // statistic computation.
1081 InstrToInstrs ADRPToReachingDefs;
1082 reachedUsesToDefs(ADRPToReachingDefs, ColorOpToReachedUses, RegToId, true);
1084 // Compute LOH for ADRP.
1085 computeADRP(ADRPToReachingDefs, *ARM64FI, MDT);
1086 delete[] ColorOpToReachedUses;
1088 // Continue with general ADRP -> ADD/LDR -> LDR/STR pattern.
1089 ColorOpToReachedUses = new InstrToInstrs[NbReg];
1091 // first perform a regular reaching def analysis.
1092 reachingDef(MF, ColorOpToReachedUses, RegToId, false, DummyOp);
1093 DEBUG(dbgs() << "All reaching defs\n");
1094 DEBUG(printReachingDef(ColorOpToReachedUses, NbReg, TRI, IdToReg));
1096 // Turn that into a use to defs to ease statistic computation.
1097 InstrToInstrs UsesToReachingDefs;
1098 reachedUsesToDefs(UsesToReachingDefs, ColorOpToReachedUses, RegToId, false);
1100 // Compute other than AdrpAdrp LOH.
1101 computeOthers(UsesToReachingDefs, ColorOpToReachedUses, *ARM64FI, RegToId,
1103 delete[] ColorOpToReachedUses;
1105 if (BasicBlockScopeOnly)
1106 MF.DeleteMachineInstr(DummyOp);
1111 /// createARM64CollectLOHPass - returns an instance of the Statistic for
1112 /// linker optimization pass.
1113 FunctionPass *llvm::createARM64CollectLOHPass() {
1114 return new ARM64CollectLOH();