1 //===------------- llvm/unittest/CodeGen/InstrRefLDVTest.cpp --------------===//
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 #include "llvm/CodeGen/MIRParser/MIRParser.h"
10 #include "llvm/CodeGen/MachineModuleInfo.h"
11 #include "llvm/CodeGen/TargetLowering.h"
12 #include "llvm/CodeGen/TargetSubtargetInfo.h"
13 #include "llvm/IR/DIBuilder.h"
14 #include "llvm/IR/DebugInfoMetadata.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include "llvm/MC/TargetRegistry.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/TargetSelect.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetOptions.h"
21 
22 #include "../lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.h"
23 
24 #include "gtest/gtest.h"
25 
26 using namespace llvm;
27 using namespace LiveDebugValues;
28 
29 // Include helper functions to ease the manipulation of MachineFunctions
30 #include "MFCommon.inc"
31 
32 class InstrRefLDVTest : public testing::Test {
33 public:
34   friend class InstrRefBasedLDV;
35   using MLocTransferMap = InstrRefBasedLDV::MLocTransferMap;
36 
37   LLVMContext Ctx;
38   std::unique_ptr<Module> Mod;
39   std::unique_ptr<TargetMachine> Machine;
40   std::unique_ptr<MachineFunction> MF;
41   std::unique_ptr<MachineDominatorTree> DomTree;
42   std::unique_ptr<MachineModuleInfo> MMI;
43   DICompileUnit *OurCU;
44   DIFile *OurFile;
45   DISubprogram *OurFunc;
46   DILexicalBlock *OurBlock, *AnotherBlock;
47   DISubprogram *ToInlineFunc;
48   DILexicalBlock *ToInlineBlock;
49   DILocalVariable *FuncVariable;
50   DIBasicType *LongInt;
51   DIExpression *EmptyExpr;
52   LiveDebugValues::OverlapMap Overlaps;
53 
54   DebugLoc OutermostLoc, InBlockLoc, NotNestedBlockLoc, InlinedLoc;
55 
56   MachineBasicBlock *MBB0, *MBB1, *MBB2, *MBB3, *MBB4;
57 
58   std::unique_ptr<InstrRefBasedLDV> LDV;
59   std::unique_ptr<MLocTracker> MTracker;
60   std::unique_ptr<VLocTracker> VTracker;
61 
62   SmallString<256> MIRStr;
63 
64   InstrRefLDVTest() : Ctx(), Mod(std::make_unique<Module>("beehives", Ctx)) {}
65 
66   void SetUp() {
67     // Boilerplate that creates a MachineFunction and associated blocks.
68 
69     Mod->setDataLayout("e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-"
70                        "n8:16:32:64-S128");
71     Triple TargetTriple("x86_64--");
72     std::string Error;
73     const Target *T = TargetRegistry::lookupTarget("", TargetTriple, Error);
74     if (!T)
75       GTEST_SKIP();
76 
77     TargetOptions Options;
78     Machine = std::unique_ptr<TargetMachine>(
79         T->createTargetMachine(Triple::normalize("x86_64--"), "", "", Options,
80                                None, None, CodeGenOpt::Aggressive));
81 
82     auto Type = FunctionType::get(Type::getVoidTy(Ctx), false);
83     auto F =
84         Function::Create(Type, GlobalValue::ExternalLinkage, "Test", &*Mod);
85 
86     unsigned FunctionNum = 42;
87     MMI = std::make_unique<MachineModuleInfo>((LLVMTargetMachine *)&*Machine);
88     const TargetSubtargetInfo &STI = *Machine->getSubtargetImpl(*F);
89 
90     MF = std::make_unique<MachineFunction>(*F, (LLVMTargetMachine &)*Machine,
91                                            STI, FunctionNum, *MMI);
92 
93     // Create metadata: CU, subprogram, some blocks and an inline function
94     // scope.
95     DIBuilder DIB(*Mod);
96     OurFile = DIB.createFile("xyzzy.c", "/cave");
97     OurCU =
98         DIB.createCompileUnit(dwarf::DW_LANG_C99, OurFile, "nou", false, "", 0);
99     auto OurSubT = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
100     OurFunc =
101         DIB.createFunction(OurCU, "bees", "", OurFile, 1, OurSubT, 1,
102                            DINode::FlagZero, DISubprogram::SPFlagDefinition);
103     F->setSubprogram(OurFunc);
104     OurBlock = DIB.createLexicalBlock(OurFunc, OurFile, 2, 3);
105     AnotherBlock = DIB.createLexicalBlock(OurFunc, OurFile, 2, 6);
106     ToInlineFunc =
107         DIB.createFunction(OurFile, "shoes", "", OurFile, 10, OurSubT, 10,
108                            DINode::FlagZero, DISubprogram::SPFlagDefinition);
109 
110     // Make some nested scopes.
111     OutermostLoc = DILocation::get(Ctx, 3, 1, OurFunc);
112     InBlockLoc = DILocation::get(Ctx, 4, 1, OurBlock);
113     InlinedLoc = DILocation::get(Ctx, 10, 1, ToInlineFunc, InBlockLoc.get());
114 
115     // Make a scope that isn't nested within the others.
116     NotNestedBlockLoc = DILocation::get(Ctx, 4, 1, AnotherBlock);
117 
118     LongInt = DIB.createBasicType("long", 64, llvm::dwarf::DW_ATE_unsigned);
119     FuncVariable = DIB.createAutoVariable(OurFunc, "lala", OurFile, 1, LongInt);
120     EmptyExpr = DIExpression::get(Ctx, {});
121 
122     DIB.finalize();
123   }
124 
125   Register getRegByName(const char *WantedName) {
126     auto *TRI = MF->getRegInfo().getTargetRegisterInfo();
127     // Slow, but works.
128     for (unsigned int I = 1; I < TRI->getNumRegs(); ++I) {
129       const char *Name = TRI->getName(I);
130       if (strcmp(WantedName, Name) == 0)
131         return I;
132     }
133 
134     // If this ever fails, something is very wrong with this unit test.
135     llvm_unreachable("Can't find register by name");
136   }
137 
138   InstrRefBasedLDV *setupLDVObj(MachineFunction *MF) {
139     // Create a new LDV object, and plug some relevant object ptrs into it.
140     LDV = std::make_unique<InstrRefBasedLDV>();
141     const TargetSubtargetInfo &STI = MF->getSubtarget();
142     LDV->TII = STI.getInstrInfo();
143     LDV->TRI = STI.getRegisterInfo();
144     LDV->TFI = STI.getFrameLowering();
145     LDV->MFI = &MF->getFrameInfo();
146     LDV->MRI = &MF->getRegInfo();
147 
148     DomTree = std::make_unique<MachineDominatorTree>(*MF);
149     LDV->DomTree = &*DomTree;
150 
151     // Future work: unit tests for mtracker / vtracker / ttracker.
152 
153     // Setup things like the artifical block map, and BlockNo <=> RPO Order
154     // mappings.
155     LDV->initialSetup(*MF);
156     LDV->LS.initialize(*MF);
157     addMTracker(MF);
158     return &*LDV;
159   }
160 
161   void addMTracker(MachineFunction *MF) {
162     ASSERT_TRUE(LDV);
163     // Add a machine-location-tracking object to LDV. Don't initialize any
164     // register locations within it though.
165     const TargetSubtargetInfo &STI = MF->getSubtarget();
166     MTracker = std::make_unique<MLocTracker>(
167           *MF, *LDV->TII, *LDV->TRI, *STI.getTargetLowering());
168     LDV->MTracker = &*MTracker;
169   }
170 
171   void addVTracker() {
172     ASSERT_TRUE(LDV);
173     VTracker = std::make_unique<VLocTracker>(Overlaps, EmptyExpr);
174     LDV->VTracker = &*VTracker;
175   }
176 
177   // Some routines for bouncing into LDV,
178   void buildMLocValueMap(ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
179                          SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
180     LDV->buildMLocValueMap(*MF, MInLocs, MOutLocs, MLocTransfer);
181   }
182 
183   void placeMLocPHIs(MachineFunction &MF,
184                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
185                      ValueIDNum **MInLocs,
186                      SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
187     LDV->placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
188   }
189 
190   Optional<ValueIDNum>
191   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
192               const InstrRefBasedLDV::LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
193               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
194     return LDV->pickVPHILoc(MBB, Var, LiveOuts, MOutLocs, BlockOrders);
195   }
196 
197   bool vlocJoin(MachineBasicBlock &MBB, InstrRefBasedLDV::LiveIdxT &VLOCOutLocs,
198                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
199                 DbgValue &InLoc) {
200     return LDV->vlocJoin(MBB, VLOCOutLocs, BlocksToExplore, InLoc);
201   }
202 
203   void buildVLocValueMap(const DILocation *DILoc,
204                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
205                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
206                     InstrRefBasedLDV::LiveInsT &Output, ValueIDNum **MOutLocs,
207                     ValueIDNum **MInLocs,
208                     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
209     LDV->buildVLocValueMap(DILoc, VarsWeCareAbout, AssignBlocks, Output,
210                            MOutLocs, MInLocs, AllTheVLocs);
211   }
212 
213   void initValueArray(ValueIDNum **Nums, unsigned Blks, unsigned Locs) {
214     for (unsigned int I = 0; I < Blks; ++I)
215       for (unsigned int J = 0; J < Locs; ++J)
216         Nums[I][J] = ValueIDNum::EmptyValue;
217   }
218 
219   void setupSingleBlock() {
220     // Add an entry block with nothing but 'ret void' in it.
221     Function &F = const_cast<llvm::Function &>(MF->getFunction());
222     auto *BB0 = BasicBlock::Create(Ctx, "entry", &F);
223     IRBuilder<> IRB(BB0);
224     IRB.CreateRetVoid();
225     MBB0 = MF->CreateMachineBasicBlock(BB0);
226     MF->insert(MF->end(), MBB0);
227     MF->RenumberBlocks();
228 
229     setupLDVObj(&*MF);
230   }
231 
232   void setupDiamondBlocks() {
233     //        entry
234     //        /  \
235     //      br1  br2
236     //        \  /
237     //         ret
238     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
239     auto *BB0 = BasicBlock::Create(Ctx, "a", &F);
240     auto *BB1 = BasicBlock::Create(Ctx, "b", &F);
241     auto *BB2 = BasicBlock::Create(Ctx, "c", &F);
242     auto *BB3 = BasicBlock::Create(Ctx, "d", &F);
243     IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3);
244     IRB0.CreateBr(BB1);
245     IRB1.CreateBr(BB2);
246     IRB2.CreateBr(BB3);
247     IRB3.CreateRetVoid();
248     MBB0 = MF->CreateMachineBasicBlock(BB0);
249     MF->insert(MF->end(), MBB0);
250     MBB1 = MF->CreateMachineBasicBlock(BB1);
251     MF->insert(MF->end(), MBB1);
252     MBB2 = MF->CreateMachineBasicBlock(BB2);
253     MF->insert(MF->end(), MBB2);
254     MBB3 = MF->CreateMachineBasicBlock(BB3);
255     MF->insert(MF->end(), MBB3);
256     MBB0->addSuccessor(MBB1);
257     MBB0->addSuccessor(MBB2);
258     MBB1->addSuccessor(MBB3);
259     MBB2->addSuccessor(MBB3);
260     MF->RenumberBlocks();
261 
262     setupLDVObj(&*MF);
263   }
264 
265   void setupSimpleLoop() {
266     //    entry
267     //     |
268     //     |/-----\
269     //    loopblk |
270     //     |\-----/
271     //     |
272     //     ret
273     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
274     auto *BB0 = BasicBlock::Create(Ctx, "entry", &F);
275     auto *BB1 = BasicBlock::Create(Ctx, "loop", &F);
276     auto *BB2 = BasicBlock::Create(Ctx, "ret", &F);
277     IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2);
278     IRB0.CreateBr(BB1);
279     IRB1.CreateBr(BB2);
280     IRB2.CreateRetVoid();
281     MBB0 = MF->CreateMachineBasicBlock(BB0);
282     MF->insert(MF->end(), MBB0);
283     MBB1 = MF->CreateMachineBasicBlock(BB1);
284     MF->insert(MF->end(), MBB1);
285     MBB2 = MF->CreateMachineBasicBlock(BB2);
286     MF->insert(MF->end(), MBB2);
287     MBB0->addSuccessor(MBB1);
288     MBB1->addSuccessor(MBB2);
289     MBB1->addSuccessor(MBB1);
290     MF->RenumberBlocks();
291 
292     setupLDVObj(&*MF);
293   }
294 
295   void setupNestedLoops() {
296     //    entry
297     //     |
298     //    loop1
299     //     ^\
300     //     | \    /-\
301     //     |  loop2  |
302     //     |  /   \-/
303     //     ^ /
304     //     join
305     //     |
306     //     ret
307     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
308     auto *BB0 = BasicBlock::Create(Ctx, "entry", &F);
309     auto *BB1 = BasicBlock::Create(Ctx, "loop1", &F);
310     auto *BB2 = BasicBlock::Create(Ctx, "loop2", &F);
311     auto *BB3 = BasicBlock::Create(Ctx, "join", &F);
312     auto *BB4 = BasicBlock::Create(Ctx, "ret", &F);
313     IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4);
314     IRB0.CreateBr(BB1);
315     IRB1.CreateBr(BB2);
316     IRB2.CreateBr(BB3);
317     IRB3.CreateBr(BB4);
318     IRB4.CreateRetVoid();
319     MBB0 = MF->CreateMachineBasicBlock(BB0);
320     MF->insert(MF->end(), MBB0);
321     MBB1 = MF->CreateMachineBasicBlock(BB1);
322     MF->insert(MF->end(), MBB1);
323     MBB2 = MF->CreateMachineBasicBlock(BB2);
324     MF->insert(MF->end(), MBB2);
325     MBB3 = MF->CreateMachineBasicBlock(BB3);
326     MF->insert(MF->end(), MBB3);
327     MBB4 = MF->CreateMachineBasicBlock(BB4);
328     MF->insert(MF->end(), MBB4);
329     MBB0->addSuccessor(MBB1);
330     MBB1->addSuccessor(MBB2);
331     MBB2->addSuccessor(MBB2);
332     MBB2->addSuccessor(MBB3);
333     MBB3->addSuccessor(MBB1);
334     MBB3->addSuccessor(MBB4);
335     MF->RenumberBlocks();
336 
337     setupLDVObj(&*MF);
338   }
339 
340   void setupNoDominatingLoop() {
341     //           entry
342     //            / \
343     //           /   \
344     //          /     \
345     //        head1   head2
346     //        ^  \   /   ^
347     //        ^   \ /    ^
348     //        \-joinblk -/
349     //             |
350     //            ret
351     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
352     auto *BB0 = BasicBlock::Create(Ctx, "entry", &F);
353     auto *BB1 = BasicBlock::Create(Ctx, "head1", &F);
354     auto *BB2 = BasicBlock::Create(Ctx, "head2", &F);
355     auto *BB3 = BasicBlock::Create(Ctx, "joinblk", &F);
356     auto *BB4 = BasicBlock::Create(Ctx, "ret", &F);
357     IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4);
358     IRB0.CreateBr(BB1);
359     IRB1.CreateBr(BB2);
360     IRB2.CreateBr(BB3);
361     IRB3.CreateBr(BB4);
362     IRB4.CreateRetVoid();
363     MBB0 = MF->CreateMachineBasicBlock(BB0);
364     MF->insert(MF->end(), MBB0);
365     MBB1 = MF->CreateMachineBasicBlock(BB1);
366     MF->insert(MF->end(), MBB1);
367     MBB2 = MF->CreateMachineBasicBlock(BB2);
368     MF->insert(MF->end(), MBB2);
369     MBB3 = MF->CreateMachineBasicBlock(BB3);
370     MF->insert(MF->end(), MBB3);
371     MBB4 = MF->CreateMachineBasicBlock(BB4);
372     MF->insert(MF->end(), MBB4);
373     MBB0->addSuccessor(MBB1);
374     MBB0->addSuccessor(MBB2);
375     MBB1->addSuccessor(MBB3);
376     MBB2->addSuccessor(MBB3);
377     MBB3->addSuccessor(MBB1);
378     MBB3->addSuccessor(MBB2);
379     MBB3->addSuccessor(MBB4);
380     MF->RenumberBlocks();
381 
382     setupLDVObj(&*MF);
383   }
384 
385   void setupBadlyNestedLoops() {
386     //           entry
387     //             |
388     //           loop1 -o
389     //             | ^
390     //             | ^
391     //           loop2 -o
392     //             | ^
393     //             | ^
394     //           loop3 -o
395     //             |
396     //            ret
397     //
398     // NB: the loop blocks self-loop, which is a bit too fiddly to draw on
399     // accurately.
400     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
401     auto *BB0 = BasicBlock::Create(Ctx, "entry", &F);
402     auto *BB1 = BasicBlock::Create(Ctx, "loop1", &F);
403     auto *BB2 = BasicBlock::Create(Ctx, "loop2", &F);
404     auto *BB3 = BasicBlock::Create(Ctx, "loop3", &F);
405     auto *BB4 = BasicBlock::Create(Ctx, "ret", &F);
406     IRBuilder<> IRB0(BB0), IRB1(BB1), IRB2(BB2), IRB3(BB3), IRB4(BB4);
407     IRB0.CreateBr(BB1);
408     IRB1.CreateBr(BB2);
409     IRB2.CreateBr(BB3);
410     IRB3.CreateBr(BB4);
411     IRB4.CreateRetVoid();
412     MBB0 = MF->CreateMachineBasicBlock(BB0);
413     MF->insert(MF->end(), MBB0);
414     MBB1 = MF->CreateMachineBasicBlock(BB1);
415     MF->insert(MF->end(), MBB1);
416     MBB2 = MF->CreateMachineBasicBlock(BB2);
417     MF->insert(MF->end(), MBB2);
418     MBB3 = MF->CreateMachineBasicBlock(BB3);
419     MF->insert(MF->end(), MBB3);
420     MBB4 = MF->CreateMachineBasicBlock(BB4);
421     MF->insert(MF->end(), MBB4);
422     MBB0->addSuccessor(MBB1);
423     MBB1->addSuccessor(MBB1);
424     MBB1->addSuccessor(MBB2);
425     MBB2->addSuccessor(MBB1);
426     MBB2->addSuccessor(MBB2);
427     MBB2->addSuccessor(MBB3);
428     MBB3->addSuccessor(MBB2);
429     MBB3->addSuccessor(MBB3);
430     MBB3->addSuccessor(MBB4);
431     MF->RenumberBlocks();
432 
433     setupLDVObj(&*MF);
434   }
435 
436   MachineFunction *readMIRBlock(const char *Input) {
437     MIRStr.clear();
438     StringRef S = Twine(Twine(R"MIR(
439 --- |
440   target triple = "x86_64-unknown-linux-gnu"
441   define void @test() { ret void }
442 ...
443 ---
444 name: test
445 tracksRegLiveness: true
446 stack:
447   - { id: 0, name: '', type: spill-slot, offset: -16, size: 8, alignment: 8,
448       stack-id: default, callee-saved-register: '', callee-saved-restored: true,
449       debug-info-variable: '', debug-info-expression: '', debug-info-location: '' }
450 body:  |
451    bb.0:
452     liveins: $rdi, $rsi
453 )MIR") + Twine(Input) + Twine("...\n"))
454                       .toNullTerminatedStringRef(MIRStr);
455     ;
456 
457     // Clear the "test" function from MMI if it's still present.
458     if (Function *Fn = Mod->getFunction("test"))
459       MMI->deleteMachineFunctionFor(*Fn);
460 
461     auto MemBuf = MemoryBuffer::getMemBuffer(S, "<input>");
462     auto MIRParse = createMIRParser(std::move(MemBuf), Ctx);
463     Mod = MIRParse->parseIRModule();
464     assert(Mod);
465     Mod->setDataLayout("e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-"
466                        "n8:16:32:64-S128");
467 
468     bool Result = MIRParse->parseMachineFunctions(*Mod, *MMI);
469     assert(!Result && "Failed to parse unit test machine function?");
470     (void)Result;
471 
472     Function *Fn = Mod->getFunction("test");
473     assert(Fn && "Failed to parse a unit test module string?");
474     Fn->setSubprogram(OurFunc);
475     return MMI->getMachineFunction(*Fn);
476   }
477 
478   void
479   produceMLocTransferFunction(MachineFunction &MF,
480                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
481                               unsigned MaxNumBlocks) {
482     LDV->produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
483   }
484 };
485 
486 TEST_F(InstrRefLDVTest, MTransferDefs) {
487   MachineFunction *MF = readMIRBlock(
488    "    $rax = MOV64ri 0\n"
489    "    RET64 $rax\n");
490   setupLDVObj(MF);
491 
492   // We should start with only SP tracked.
493   EXPECT_TRUE(MTracker->getNumLocs() == 1);
494 
495   SmallVector<MLocTransferMap, 1> TransferMap;
496   TransferMap.resize(1);
497   produceMLocTransferFunction(*MF, TransferMap, 1);
498 
499   // Code contains only one register write: that should assign to each of the
500   // aliasing registers. Test that all of them get locations, and have a
501   // corresponding def at the first instr in the function.
502   const char *RegNames[] = {"RAX", "HAX", "EAX", "AX", "AH", "AL"};
503   EXPECT_TRUE(MTracker->getNumLocs() == 7);
504   for (const char *RegName : RegNames) {
505     Register R = getRegByName(RegName);
506     ASSERT_TRUE(MTracker->isRegisterTracked(R));
507     LocIdx L = MTracker->getRegMLoc(R);
508     ValueIDNum V = MTracker->readReg(R);
509     // Value of this register should be: block zero, instruction 1, and the
510     // location it's defined in is itself.
511     ValueIDNum ToCmp(0, 1, L);
512     EXPECT_EQ(V, ToCmp);
513   }
514 
515   // Do the same again, but with an aliasing write. This should write to all
516   // the same registers again, except $ah and $hax (the upper 8 bits of $ax
517   // and 32 bits of $rax resp.).
518   MF = readMIRBlock(
519    "    $rax = MOV64ri 0\n"
520    "    $al = MOV8ri 0\n"
521    "    RET64 $rax\n");
522   setupLDVObj(MF);
523   TransferMap.clear();
524   TransferMap.resize(1);
525   produceMLocTransferFunction(*MF, TransferMap, 1);
526 
527   auto TestRegSetSite = [&](const char *Name, unsigned InstrNum) {
528     Register R = getRegByName(Name);
529     ASSERT_TRUE(MTracker->isRegisterTracked(R));
530     LocIdx L = MTracker->getRegMLoc(R);
531     ValueIDNum V = MTracker->readMLoc(L);
532     ValueIDNum ToCmp(0, InstrNum, L);
533     EXPECT_EQ(V, ToCmp);
534   };
535 
536   TestRegSetSite("AL", 2);
537   TestRegSetSite("AH", 1);
538   TestRegSetSite("AX", 2);
539   TestRegSetSite("EAX", 2);
540   TestRegSetSite("HAX", 1);
541   TestRegSetSite("RAX", 2);
542 
543   // This call should:
544   //  * Def rax via the implicit-def,
545   //  * Clobber rsi/rdi and all their subregs, via the register mask
546   //  * Same for rcx, despite it not being a use in the instr, it's in the mask
547   //  * NOT clobber $rsp / $esp $ sp, LiveDebugValues deliberately ignores
548   //    these.
549   //  * NOT clobber $rbx, because it's non-volatile
550   //  * Not track every other register in the machine, only those needed.
551  MF = readMIRBlock(
552    "    $rax = MOV64ri 0\n" // instr 1
553    "    $rbx = MOV64ri 0\n" // instr 2
554    "    $rcx = MOV64ri 0\n" // instr 3
555    "    $rdi = MOV64ri 0\n" // instr 4
556    "    $rsi = MOV64ri 0\n" // instr 5
557    "    CALL64r $rax, csr_64, implicit $rsp, implicit $ssp, implicit $rdi, implicit $rsi, implicit-def $rsp, implicit-def $ssp, implicit-def $rax, implicit-def $esp, implicit-def $sp\n\n\n\n" // instr 6
558    "    RET64 $rax\n"); // instr 7
559   setupLDVObj(MF);
560   TransferMap.clear();
561   TransferMap.resize(1);
562   produceMLocTransferFunction(*MF, TransferMap, 1);
563 
564   const char *RegsSetInCall[] = {"AL",  "AH",  "AX", "EAX", "HAX", "RAX",
565                                  "DIL", "DIH", "DI", "EDI", "HDI", "RDI",
566                                  "SIL", "SIH", "SI", "ESI", "HSI", "RSI",
567                                  "CL",  "CH",  "CX", "ECX", "HCX", "RCX"};
568   for (const char *RegSetInCall : RegsSetInCall)
569     TestRegSetSite(RegSetInCall, 6);
570 
571   const char *RegsLeftAlone[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"};
572   for (const char *RegLeftAlone : RegsLeftAlone)
573     TestRegSetSite(RegLeftAlone, 2);
574 
575   // Stack pointer should be the live-in to the function, instruction zero.
576   TestRegSetSite("RSP", 0);
577   // These stack regs should not be tracked either. Nor the (fake) subregs.
578   EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("ESP")));
579   EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SP")));
580   EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SPL")));
581   EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("SPH")));
582   EXPECT_FALSE(MTracker->isRegisterTracked(getRegByName("HSP")));
583 
584   // Should only be tracking: 6 x {A, B, C, DI, SI} registers = 30,
585   // Plus RSP, SSP = 32.
586   EXPECT_EQ(32u, MTracker->getNumLocs());
587 
588 
589   // When we DBG_PHI something, we should track all its subregs.
590   MF = readMIRBlock(
591    "    DBG_PHI $rdi, 0\n"
592    "    RET64\n");
593   setupLDVObj(MF);
594   TransferMap.clear();
595   TransferMap.resize(1);
596   produceMLocTransferFunction(*MF, TransferMap, 1);
597 
598   // All DI regs and RSP tracked.
599   EXPECT_EQ(7u, MTracker->getNumLocs());
600 
601   // All the DI registers should have block live-in values, i.e. the argument
602   // to the function.
603   const char *DIRegs[] = {"DIL", "DIH", "DI", "EDI", "HDI", "RDI"};
604   for (const char *DIReg : DIRegs)
605     TestRegSetSite(DIReg, 0);
606 }
607 
608 TEST_F(InstrRefLDVTest, MTransferMeta) {
609   // Meta instructions should not have any effect on register values.
610   SmallVector<MLocTransferMap, 1> TransferMap;
611   MachineFunction *MF = readMIRBlock(
612    "    $rax = MOV64ri 0\n"
613    "    $rax = IMPLICIT_DEF\n"
614    "    $rax = KILL killed $rax\n"
615    "    RET64 $rax\n");
616   setupLDVObj(MF);
617   TransferMap.clear();
618   TransferMap.resize(1);
619   produceMLocTransferFunction(*MF, TransferMap, 1);
620 
621   LocIdx RaxLoc = MTracker->getRegMLoc(getRegByName("RAX"));
622   ValueIDNum V = MTracker->readMLoc(RaxLoc);
623   // Def of rax should be from instruction 1, i.e., unmodified.
624   ValueIDNum Cmp(0, 1, RaxLoc);
625   EXPECT_EQ(Cmp, V);
626 }
627 
628 TEST_F(InstrRefLDVTest, MTransferCopies) {
629   SmallVector<MLocTransferMap, 1> TransferMap;
630   // This memory spill should be recognised, and a spill slot created.
631   MachineFunction *MF = readMIRBlock(
632    "    $rax = MOV64ri 0\n"
633    "    MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n"
634    "    RET64 $rax\n");
635   setupLDVObj(MF);
636   TransferMap.clear();
637   TransferMap.resize(1);
638   produceMLocTransferFunction(*MF, TransferMap, 1);
639 
640   // Check that the spill location contains the value defined in rax by
641   // instruction 1. The MIR header says -16 offset, but it's stored as -8;
642   // it's not completely clear why, but here we only care about correctly
643   // identifying the slot, not that all the surrounding data is correct.
644   SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)};
645   SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L);
646   unsigned SpillLocID = MTracker->getLocID(SpillNo, {64, 0});
647   LocIdx SpillLoc = MTracker->getSpillMLoc(SpillLocID);
648   ValueIDNum V = MTracker->readMLoc(SpillLoc);
649   Register RAX = getRegByName("RAX");
650   LocIdx RaxLoc = MTracker->getRegMLoc(RAX);
651   ValueIDNum Cmp(0, 1, RaxLoc);
652   EXPECT_EQ(V, Cmp);
653 
654   // A spill and restore should be recognised.
655   MF = readMIRBlock(
656    "    $rax = MOV64ri 0\n"
657    "    MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n"
658    "    $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n"
659    "    RET64\n");
660   setupLDVObj(MF);
661   TransferMap.clear();
662   TransferMap.resize(1);
663   produceMLocTransferFunction(*MF, TransferMap, 1);
664 
665   // Test that rbx contains rax from instruction 1.
666   RAX = getRegByName("RAX");
667   RaxLoc = MTracker->getRegMLoc(RAX);
668   Register RBX = getRegByName("RBX");
669   LocIdx RbxLoc = MTracker->getRegMLoc(RBX);
670   Cmp = ValueIDNum(0, 1, RaxLoc);
671   ValueIDNum RbxVal = MTracker->readMLoc(RbxLoc);
672   EXPECT_EQ(RbxVal, Cmp);
673 
674   // Testing that all the subregisters are transferred happens in
675   // MTransferSubregSpills.
676 
677   // Copies and x86 movs should be recognised and honoured. In addition, all
678   // of the subregisters should be copied across too.
679   MF = readMIRBlock(
680    "    $rax = MOV64ri 0\n"
681    "    $rcx = COPY $rax\n"
682    "    $rbx = MOV64rr $rcx\n"
683    "    RET64\n");
684   setupLDVObj(MF);
685   TransferMap.clear();
686   TransferMap.resize(1);
687   produceMLocTransferFunction(*MF, TransferMap, 1);
688 
689   const char *ARegs[] = {"AL", "AH", "AX", "EAX", "HAX", "RAX"};
690   const char *BRegs[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"};
691   const char *CRegs[] = {"CL", "CH", "CX", "ECX", "HCX", "RCX"};
692   auto CheckReg = [&](unsigned int I) {
693     LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I]));
694     LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I]));
695     LocIdx C = MTracker->getRegMLoc(getRegByName(CRegs[I]));
696     ValueIDNum ARefVal(0, 1, A);
697     ValueIDNum AVal = MTracker->readMLoc(A);
698     ValueIDNum BVal = MTracker->readMLoc(B);
699     ValueIDNum CVal = MTracker->readMLoc(C);
700     EXPECT_EQ(ARefVal, AVal);
701     EXPECT_EQ(ARefVal, BVal);
702     EXPECT_EQ(ARefVal, CVal);
703   };
704 
705   for (unsigned int I = 0; I < 6; ++I)
706     CheckReg(I);
707 
708   // When we copy to a subregister, the super-register should be def'd too: it's
709   // value will have changed.
710   MF = readMIRBlock(
711    "    $rax = MOV64ri 0\n"
712    "    $ecx = COPY $eax\n"
713    "    RET64\n");
714   setupLDVObj(MF);
715   TransferMap.clear();
716   TransferMap.resize(1);
717   produceMLocTransferFunction(*MF, TransferMap, 1);
718 
719   // First four regs [al, ah, ax, eax] should be copied to *cx.
720   for (unsigned int I = 0; I < 4; ++I) {
721     LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I]));
722     LocIdx C = MTracker->getRegMLoc(getRegByName(CRegs[I]));
723     ValueIDNum ARefVal(0, 1, A);
724     ValueIDNum AVal = MTracker->readMLoc(A);
725     ValueIDNum CVal = MTracker->readMLoc(C);
726     EXPECT_EQ(ARefVal, AVal);
727     EXPECT_EQ(ARefVal, CVal);
728   }
729 
730   // But rcx should contain a value defined by the COPY.
731   LocIdx RcxLoc = MTracker->getRegMLoc(getRegByName("RCX"));
732   ValueIDNum RcxVal = MTracker->readMLoc(RcxLoc);
733   ValueIDNum RcxDefVal(0, 2, RcxLoc); // instr 2 -> the copy
734   EXPECT_EQ(RcxVal, RcxDefVal);
735 }
736 
737 TEST_F(InstrRefLDVTest, MTransferSubregSpills) {
738   SmallVector<MLocTransferMap, 1> TransferMap;
739   MachineFunction *MF = readMIRBlock(
740    "    $rax = MOV64ri 0\n"
741    "    MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n"
742    "    $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n"
743    "    RET64\n");
744   setupLDVObj(MF);
745   TransferMap.clear();
746   TransferMap.resize(1);
747   produceMLocTransferFunction(*MF, TransferMap, 1);
748 
749   // Check that all the subregs of rax and rbx contain the same values. One
750   // should completely transfer to the other.
751   const char *ARegs[] = {"AL", "AH", "AX", "EAX", "HAX", "RAX"};
752   const char *BRegs[] = {"BL", "BH", "BX", "EBX", "HBX", "RBX"};
753   for (unsigned int I = 0; I < 6; ++I) {
754     LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I]));
755     LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I]));
756     EXPECT_EQ(MTracker->readMLoc(A), MTracker->readMLoc(B));
757   }
758 
759   // Explicitly check what's in the different subreg slots, on the stack.
760   // Pair up subreg idx fields with the corresponding subregister in $rax.
761   MLocTracker::StackSlotPos SubRegIdxes[] = {{8, 0}, {8, 8}, {16, 0}, {32, 0}, {64, 0}};
762   const char *SubRegNames[] = {"AL", "AH", "AX", "EAX", "RAX"};
763   for (unsigned int I = 0; I < 5; ++I) {
764     // Value number where it's defined,
765     LocIdx RegLoc = MTracker->getRegMLoc(getRegByName(SubRegNames[I]));
766     ValueIDNum DefNum(0, 1, RegLoc);
767     // Read the corresponding subreg field from the stack.
768     SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)};
769     SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L);
770     unsigned SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]);
771     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
772     ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc);
773     EXPECT_EQ(DefNum, SpillValue);
774   }
775 
776   // If we have exactly the same code, but we write $eax to the stack slot after
777   // $rax, then we should still have exactly the same output in the lower five
778   // subregisters. Storing $eax to the start of the slot will overwrite with the
779   // same values. $rax, as an aliasing register, should be reset to something
780   // else by that write.
781   // In theory, we could try and recognise that we're writing the _same_ values
782   // to the stack again, and so $rax doesn't need to be reset to something else.
783   // It seems vanishingly unlikely that LLVM would generate such code though,
784   // so the benefits would be small.
785   MF = readMIRBlock(
786    "    $rax = MOV64ri 0\n"
787    "    MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n"
788    "    MOV32mr $rsp, 1, $noreg, 16, $noreg, $eax :: (store 4 into %stack.0)\n"
789    "    $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n"
790    "    RET64\n");
791   setupLDVObj(MF);
792   TransferMap.clear();
793   TransferMap.resize(1);
794   produceMLocTransferFunction(*MF, TransferMap, 1);
795 
796   // Check lower five registers up to and include $eax == $ebx,
797   for (unsigned int I = 0; I < 5; ++I) {
798     LocIdx A = MTracker->getRegMLoc(getRegByName(ARegs[I]));
799     LocIdx B = MTracker->getRegMLoc(getRegByName(BRegs[I]));
800     EXPECT_EQ(MTracker->readMLoc(A), MTracker->readMLoc(B));
801   }
802 
803   // $rbx should contain something else; today it's a def at the spill point
804   // of the 4 byte value.
805   SpillLoc L = {getRegByName("RSP"), StackOffset::getFixed(-8)};
806   SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L);
807   unsigned SpillID = MTracker->getLocID(SpillNo, {64, 0});
808   LocIdx Spill64Loc = MTracker->getSpillMLoc(SpillID);
809   ValueIDNum DefAtSpill64(0, 3, Spill64Loc);
810   LocIdx RbxLoc = MTracker->getRegMLoc(getRegByName("RBX"));
811   EXPECT_EQ(MTracker->readMLoc(RbxLoc), DefAtSpill64);
812 
813   // Same again, test that the lower four subreg slots on the stack are the
814   // value defined by $rax in instruction 1.
815   for (unsigned int I = 0; I < 4; ++I) {
816     // Value number where it's defined,
817     LocIdx RegLoc = MTracker->getRegMLoc(getRegByName(SubRegNames[I]));
818     ValueIDNum DefNum(0, 1, RegLoc);
819     // Read the corresponding subreg field from the stack.
820     SpillNo = MTracker->getOrTrackSpillLoc(L);
821     SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]);
822     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
823     ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc);
824     EXPECT_EQ(DefNum, SpillValue);
825   }
826 
827   // Stack slot for $rax should be a different value, today it's EmptyValue.
828   ValueIDNum SpillValue = MTracker->readMLoc(Spill64Loc);
829   EXPECT_EQ(SpillValue, DefAtSpill64);
830 
831   // If we write something to the stack, then over-write with some register
832   // from a completely different hierarchy, none of the "old" values should be
833   // readable.
834   // NB: slight hack, store 16 in to a 8 byte stack slot.
835   MF = readMIRBlock(
836    "    $rax = MOV64ri 0\n"
837    "    MOV64mr $rsp, 1, $noreg, 16, $noreg, $rax :: (store 8 into %stack.0)\n"
838    "    $xmm0 = IMPLICIT_DEF\n"
839    "    MOVUPDmr $rsp, 1, $noreg, 16, $noreg, killed $xmm0 :: (store (s128) into %stack.0)\n"
840    "    $rbx = MOV64rm $rsp, 1, $noreg, 0, $noreg :: (load 8 from %stack.0)\n"
841    "    RET64\n");
842   setupLDVObj(MF);
843   TransferMap.clear();
844   TransferMap.resize(1);
845   produceMLocTransferFunction(*MF, TransferMap, 1);
846 
847   for (unsigned int I = 0; I < 5; ++I) {
848     // Read subreg fields from the stack.
849     SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(L);
850     unsigned SpillID = MTracker->getLocID(SpillNo, SubRegIdxes[I]);
851     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
852     ValueIDNum SpillValue = MTracker->readMLoc(SpillLoc);
853 
854     // Value should be defined by the spill-to-xmm0 instr, get value of a def
855     // at the point of the spill.
856     ValueIDNum SpillDef(0, 4, SpillLoc);
857     EXPECT_EQ(SpillValue, SpillDef);
858   }
859 
860   // Read xmm0's position and ensure it has a value. Should be the live-in
861   // value to the block, as IMPLICIT_DEF isn't a real def.
862   SpillNo = MTracker->getOrTrackSpillLoc(L);
863   SpillID = MTracker->getLocID(SpillNo, {128, 0});
864   LocIdx Spill128Loc = MTracker->getSpillMLoc(SpillID);
865   SpillValue = MTracker->readMLoc(Spill128Loc);
866   Register XMM0 = getRegByName("XMM0");
867   LocIdx Xmm0Loc = MTracker->getRegMLoc(XMM0);
868   EXPECT_EQ(ValueIDNum(0, 0, Xmm0Loc), SpillValue);
869 
870   // What happens if we spill ah to the stack, then load al? It should find
871   // the same value.
872   MF = readMIRBlock(
873    "    $rax = MOV64ri 0\n"
874    "    MOV8mr $rsp, 1, $noreg, 16, $noreg, $ah :: (store 1 into %stack.0)\n"
875    "    $al = MOV8rm $rsp, 1, $noreg, 0, $noreg :: (load 1 from %stack.0)\n"
876    "    RET64\n");
877   setupLDVObj(MF);
878   TransferMap.clear();
879   TransferMap.resize(1);
880   produceMLocTransferFunction(*MF, TransferMap, 1);
881 
882   Register AL = getRegByName("AL");
883   Register AH = getRegByName("AH");
884   LocIdx AlLoc = MTracker->getRegMLoc(AL);
885   LocIdx AhLoc = MTracker->getRegMLoc(AH);
886   ValueIDNum AHDef(0, 1, AhLoc);
887   ValueIDNum ALValue = MTracker->readMLoc(AlLoc);
888   EXPECT_EQ(ALValue, AHDef);
889 }
890 
891 TEST_F(InstrRefLDVTest, MLocSingleBlock) {
892   // Test some very simple properties about interpreting the transfer function.
893   setupSingleBlock();
894 
895   // We should start with a single location, the stack pointer.
896   ASSERT_TRUE(MTracker->getNumLocs() == 1);
897   LocIdx RspLoc(0);
898 
899   // Set up live-in and live-out tables for this function: two locations (we
900   // add one later) in a single block.
901   ValueIDNum InLocs[2], OutLocs[2];
902   ValueIDNum *InLocsPtr[1] = {&InLocs[0]};
903   ValueIDNum *OutLocsPtr[1] = {&OutLocs[0]};
904 
905   // Transfer function: nothing.
906   SmallVector<MLocTransferMap, 1> TransferFunc;
907   TransferFunc.resize(1);
908 
909   // Try and build value maps...
910   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
911 
912   // The result should be that RSP is marked as a live-in-PHI -- this represents
913   // an argument. And as there's no transfer function, the block live-out should
914   // be the same.
915   EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc));
916   EXPECT_EQ(OutLocs[0], ValueIDNum(0, 0, RspLoc));
917 
918   // Try again, this time initialising the in-locs to be defined by an
919   // instruction. The entry block should always be re-assigned to be the
920   // arguments.
921   initValueArray(InLocsPtr, 1, 2);
922   initValueArray(OutLocsPtr, 1, 2);
923   InLocs[0] = ValueIDNum(0, 1, RspLoc);
924   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
925   EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc));
926   EXPECT_EQ(OutLocs[0], ValueIDNum(0, 0, RspLoc));
927 
928   // Now insert something into the transfer function to assign to the single
929   // machine location.
930   TransferFunc[0].insert({RspLoc, ValueIDNum(0, 1, RspLoc)});
931   initValueArray(InLocsPtr, 1, 2);
932   initValueArray(OutLocsPtr, 1, 2);
933   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
934   EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc));
935   EXPECT_EQ(OutLocs[0], ValueIDNum(0, 1, RspLoc));
936   TransferFunc[0].clear();
937 
938   // Add a new register to be tracked, and insert it into the transfer function
939   // as a copy. The output of $rax should be the live-in value of $rsp.
940   Register RAX = getRegByName("RAX");
941   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
942   TransferFunc[0].insert({RspLoc, ValueIDNum(0, 1, RspLoc)});
943   TransferFunc[0].insert({RaxLoc, ValueIDNum(0, 0, RspLoc)});
944   initValueArray(InLocsPtr, 1, 2);
945   initValueArray(OutLocsPtr, 1, 2);
946   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
947   EXPECT_EQ(InLocs[0], ValueIDNum(0, 0, RspLoc));
948   EXPECT_EQ(InLocs[1], ValueIDNum(0, 0, RaxLoc));
949   EXPECT_EQ(OutLocs[0], ValueIDNum(0, 1, RspLoc));
950   EXPECT_EQ(OutLocs[1], ValueIDNum(0, 0, RspLoc)); // Rax contains RspLoc.
951   TransferFunc[0].clear();
952 }
953 
954 TEST_F(InstrRefLDVTest, MLocDiamondBlocks) {
955   // Test that information flows from the entry block to two successors.
956   //        entry
957   //        /  \
958   //      br1  br2
959   //        \  /
960   //         ret
961   setupDiamondBlocks();
962 
963   ASSERT_TRUE(MTracker->getNumLocs() == 1);
964   LocIdx RspLoc(0);
965   Register RAX = getRegByName("RAX");
966   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
967 
968   ValueIDNum InLocs[4][2], OutLocs[4][2];
969   ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]};
970   ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]};
971 
972   // Transfer function: start with nothing.
973   SmallVector<MLocTransferMap, 1> TransferFunc;
974   TransferFunc.resize(4);
975 
976   // Name some values.
977   unsigned EntryBlk = 0, BrBlk1 = 1, BrBlk2 = 2, RetBlk = 3;
978 
979   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
980   ValueIDNum RspDefInBlk0(EntryBlk, 1, RspLoc);
981   ValueIDNum RspDefInBlk1(BrBlk1, 1, RspLoc);
982   ValueIDNum RspDefInBlk2(BrBlk2, 1, RspLoc);
983   ValueIDNum RspPHIInBlk3(RetBlk, 0, RspLoc);
984   ValueIDNum RaxLiveInBlk1(BrBlk1, 0, RaxLoc);
985   ValueIDNum RaxLiveInBlk2(BrBlk2, 0, RaxLoc);
986 
987   // With no transfer function, the live-in values to the entry block should
988   // propagate to all live-outs and the live-ins to the two successor blocks.
989   // IN ADDITION: this checks that the exit block doesn't get a PHI put in it.
990   initValueArray(InLocsPtr, 4, 2);
991   initValueArray(OutLocsPtr, 4, 2);
992   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
993   EXPECT_EQ(InLocs[0][0], LiveInRsp);
994   EXPECT_EQ(InLocs[1][0], LiveInRsp);
995   EXPECT_EQ(InLocs[2][0], LiveInRsp);
996   EXPECT_EQ(InLocs[3][0], LiveInRsp);
997   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
998   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
999   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1000   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1001   // (Skipped writing out locations for $rax).
1002 
1003   // Check that a def of $rsp in the entry block will likewise reach all the
1004   // successors.
1005   TransferFunc[0].insert({RspLoc, RspDefInBlk0});
1006   initValueArray(InLocsPtr, 4, 2);
1007   initValueArray(OutLocsPtr, 4, 2);
1008   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1009   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1010   EXPECT_EQ(InLocs[1][0], RspDefInBlk0);
1011   EXPECT_EQ(InLocs[2][0], RspDefInBlk0);
1012   EXPECT_EQ(InLocs[3][0], RspDefInBlk0);
1013   EXPECT_EQ(OutLocs[0][0], RspDefInBlk0);
1014   EXPECT_EQ(OutLocs[1][0], RspDefInBlk0);
1015   EXPECT_EQ(OutLocs[2][0], RspDefInBlk0);
1016   EXPECT_EQ(OutLocs[3][0], RspDefInBlk0);
1017   TransferFunc[0].clear();
1018 
1019   // Def in one branch of the diamond means that we need a PHI in the ret block
1020   TransferFunc[0].insert({RspLoc, RspDefInBlk0});
1021   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1022   initValueArray(InLocsPtr, 4, 2);
1023   initValueArray(OutLocsPtr, 4, 2);
1024   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1025   // This value map: like above, where RspDefInBlk0 is propagated through one
1026   // branch of the diamond, but is def'ed in the live-outs of the other. The
1027   // ret / merging block should have a PHI in its live-ins.
1028   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1029   EXPECT_EQ(InLocs[1][0], RspDefInBlk0);
1030   EXPECT_EQ(InLocs[2][0], RspDefInBlk0);
1031   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1032   EXPECT_EQ(OutLocs[0][0], RspDefInBlk0);
1033   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1034   EXPECT_EQ(OutLocs[2][0], RspDefInBlk0);
1035   EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3);
1036   TransferFunc[0].clear();
1037   TransferFunc[1].clear();
1038 
1039   // If we have differeing defs in either side of the diamond, we should
1040   // continue to produce a PHI,
1041   TransferFunc[0].insert({RspLoc, RspDefInBlk0});
1042   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1043   TransferFunc[2].insert({RspLoc, RspDefInBlk2});
1044   initValueArray(InLocsPtr, 4, 2);
1045   initValueArray(OutLocsPtr, 4, 2);
1046   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1047   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1048   EXPECT_EQ(InLocs[1][0], RspDefInBlk0);
1049   EXPECT_EQ(InLocs[2][0], RspDefInBlk0);
1050   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1051   EXPECT_EQ(OutLocs[0][0], RspDefInBlk0);
1052   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1053   EXPECT_EQ(OutLocs[2][0], RspDefInBlk2);
1054   EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3);
1055   TransferFunc[0].clear();
1056   TransferFunc[1].clear();
1057   TransferFunc[2].clear();
1058 
1059   // If we have defs of the same value on either side of the branch, a PHI will
1060   // initially be created, however value propagation should then eliminate it.
1061   // Encode this by copying the live-in value to $rax, and copying it to $rsp
1062   // from $rax in each branch of the diamond. We don't allow the definition of
1063   // arbitary values in transfer functions.
1064   TransferFunc[0].insert({RspLoc, RspDefInBlk0});
1065   TransferFunc[0].insert({RaxLoc, LiveInRsp});
1066   TransferFunc[1].insert({RspLoc, RaxLiveInBlk1});
1067   TransferFunc[2].insert({RspLoc, RaxLiveInBlk2});
1068   initValueArray(InLocsPtr, 4, 2);
1069   initValueArray(OutLocsPtr, 4, 2);
1070   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1071   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1072   EXPECT_EQ(InLocs[1][0], RspDefInBlk0);
1073   EXPECT_EQ(InLocs[2][0], RspDefInBlk0);
1074   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1075   EXPECT_EQ(OutLocs[0][0], RspDefInBlk0);
1076   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1077   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1078   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1079   TransferFunc[0].clear();
1080   TransferFunc[1].clear();
1081   TransferFunc[2].clear();
1082 }
1083 
1084 TEST_F(InstrRefLDVTest, MLocDiamondSpills) {
1085   // Test that defs in stack locations that require PHIs, cause PHIs to be
1086   // installed in aliasing locations. i.e., if there's a PHI in the lower
1087   // 8 bits of the stack, there should be PHIs for 16/32/64 bit locations
1088   // on the stack too.
1089   // Technically this isn't needed for accuracy: we should calculate PHIs
1090   // independently for each location. However, because there's an optimisation
1091   // that only places PHIs for the lower "interfering" parts of stack slots,
1092   // test for this behaviour.
1093   setupDiamondBlocks();
1094 
1095   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1096   LocIdx RspLoc(0);
1097 
1098   // Create a stack location and ensure it's tracked.
1099   SpillLoc SL = {getRegByName("RSP"), StackOffset::getFixed(-8)};
1100   SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(SL);
1101   ASSERT_EQ(MTracker->getNumLocs(), 10u); // Tracks all possible stack locs.
1102   // Locations are: RSP, stack slots from 2^3 bits wide up to 2^9 for zmm regs,
1103   // then slots for sub_8bit_hi and sub_16bit_hi ({8, 8} and {16, 16}).
1104 
1105   // Pick out the locations on the stack that various x86 regs would be written
1106   // to. HAX is the upper 16 bits of EAX.
1107   unsigned ALID = MTracker->getLocID(SpillNo, {8, 0});
1108   unsigned AHID = MTracker->getLocID(SpillNo, {8, 8});
1109   unsigned AXID = MTracker->getLocID(SpillNo, {16, 0});
1110   unsigned EAXID = MTracker->getLocID(SpillNo, {32, 0});
1111   unsigned HAXID = MTracker->getLocID(SpillNo, {16, 16});
1112   unsigned RAXID = MTracker->getLocID(SpillNo, {64, 0});
1113   LocIdx ALStackLoc = MTracker->getSpillMLoc(ALID);
1114   LocIdx AHStackLoc = MTracker->getSpillMLoc(AHID);
1115   LocIdx AXStackLoc = MTracker->getSpillMLoc(AXID);
1116   LocIdx EAXStackLoc = MTracker->getSpillMLoc(EAXID);
1117   LocIdx HAXStackLoc = MTracker->getSpillMLoc(HAXID);
1118   LocIdx RAXStackLoc = MTracker->getSpillMLoc(RAXID);
1119   // There are other locations, for things like xmm0, which we're going to
1120   // ignore here.
1121 
1122   ValueIDNum InLocs[4][10];
1123   ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]};
1124 
1125   // Transfer function: start with nothing.
1126   SmallVector<MLocTransferMap, 1> TransferFunc;
1127   TransferFunc.resize(4);
1128 
1129   // Name some values.
1130   unsigned EntryBlk = 0, Blk1 = 1, RetBlk = 3;
1131 
1132   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1133   ValueIDNum ALLiveIn(EntryBlk, 0, ALStackLoc);
1134   ValueIDNum AHLiveIn(EntryBlk, 0, AHStackLoc);
1135   ValueIDNum HAXLiveIn(EntryBlk, 0, HAXStackLoc);
1136   ValueIDNum ALPHI(RetBlk, 0, ALStackLoc);
1137   ValueIDNum AXPHI(RetBlk, 0, AXStackLoc);
1138   ValueIDNum EAXPHI(RetBlk, 0, EAXStackLoc);
1139   ValueIDNum HAXPHI(RetBlk, 0, HAXStackLoc);
1140   ValueIDNum RAXPHI(RetBlk, 0, RAXStackLoc);
1141 
1142   ValueIDNum ALDefInBlk1(Blk1, 1, ALStackLoc);
1143   ValueIDNum HAXDefInBlk1(Blk1, 1, HAXStackLoc);
1144 
1145   SmallPtrSet<MachineBasicBlock *, 4> AllBlocks{MBB0, MBB1, MBB2, MBB3};
1146 
1147   // If we put defs into one side of the diamond, for AL and HAX, then we should
1148   // find all aliasing positions have PHIs placed. This isn't technically what
1149   // the transfer function says to do: but we're testing that the optimisation
1150   // to reduce IDF calculation does the right thing.
1151   // AH should not be def'd: it don't alias AL or HAX.
1152   //
1153   // NB: we don't call buildMLocValueMap, because it will try to eliminate the
1154   // upper-slot PHIs, and succeed because of our slightly cooked transfer
1155   // function.
1156   TransferFunc[1].insert({ALStackLoc, ALDefInBlk1});
1157   TransferFunc[1].insert({HAXStackLoc, HAXDefInBlk1});
1158   initValueArray(InLocsPtr, 4, 10);
1159   placeMLocPHIs(*MF, AllBlocks, InLocsPtr, TransferFunc);
1160   EXPECT_EQ(InLocs[3][ALStackLoc.asU64()], ALPHI);
1161   EXPECT_EQ(InLocs[3][AXStackLoc.asU64()], AXPHI);
1162   EXPECT_EQ(InLocs[3][EAXStackLoc.asU64()], EAXPHI);
1163   EXPECT_EQ(InLocs[3][HAXStackLoc.asU64()], HAXPHI);
1164   EXPECT_EQ(InLocs[3][RAXStackLoc.asU64()], RAXPHI);
1165   // AH should be left untouched,
1166   EXPECT_EQ(InLocs[3][AHStackLoc.asU64()], ValueIDNum::EmptyValue);
1167 
1168 }
1169 
1170 TEST_F(InstrRefLDVTest, MLocSimpleLoop) {
1171   //    entry
1172   //     |
1173   //     |/-----\
1174   //    loopblk |
1175   //     |\-----/
1176   //     |
1177   //     ret
1178   setupSimpleLoop();
1179 
1180   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1181   LocIdx RspLoc(0);
1182   Register RAX = getRegByName("RAX");
1183   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1184 
1185   ValueIDNum InLocs[3][2], OutLocs[3][2];
1186   ValueIDNum *InLocsPtr[3] = {InLocs[0], InLocs[1], InLocs[2]};
1187   ValueIDNum *OutLocsPtr[3] = {OutLocs[0], OutLocs[1], OutLocs[2]};
1188 
1189   SmallVector<MLocTransferMap, 1> TransferFunc;
1190   TransferFunc.resize(3);
1191 
1192   // Name some values.
1193   unsigned EntryBlk = 0, LoopBlk = 1, RetBlk = 2;
1194 
1195   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1196   ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc);
1197   ValueIDNum RspDefInBlk1(LoopBlk, 1, RspLoc);
1198   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
1199   ValueIDNum RaxPHIInBlk1(LoopBlk, 0, RaxLoc);
1200   ValueIDNum RaxPHIInBlk2(RetBlk, 0, RaxLoc);
1201 
1202   // Begin test with all locations being live-through.
1203   initValueArray(InLocsPtr, 3, 2);
1204   initValueArray(OutLocsPtr, 3, 2);
1205   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1206   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1207   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1208   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1209   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1210   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1211   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1212 
1213   // Add a def of $rsp to the loop block: it should be in the live-outs, but
1214   // should cause a PHI to be placed in the live-ins. Test the transfer function
1215   // by copying that PHI into $rax in the loop, then back to $rsp in the ret
1216   // block.
1217   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1218   TransferFunc[1].insert({RaxLoc, RspPHIInBlk1});
1219   TransferFunc[2].insert({RspLoc, RaxPHIInBlk2});
1220   initValueArray(InLocsPtr, 3, 2);
1221   initValueArray(OutLocsPtr, 3, 2);
1222   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1223   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1224   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1225   EXPECT_EQ(InLocs[2][0], RspDefInBlk1);
1226   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1227   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1228   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk1);
1229   // Check rax as well,
1230   EXPECT_EQ(InLocs[0][1], LiveInRax);
1231   EXPECT_EQ(InLocs[1][1], RaxPHIInBlk1);
1232   EXPECT_EQ(InLocs[2][1], RspPHIInBlk1);
1233   EXPECT_EQ(OutLocs[0][1], LiveInRax);
1234   EXPECT_EQ(OutLocs[1][1], RspPHIInBlk1);
1235   EXPECT_EQ(OutLocs[2][1], RspPHIInBlk1);
1236   TransferFunc[1].clear();
1237   TransferFunc[2].clear();
1238 
1239   // As with the diamond case, a PHI will be created if there's a (implicit)
1240   // def in the entry block and loop block; but should be value propagated away
1241   // if it copies in the same value. Copy live-in $rsp to $rax, then copy it
1242   // into $rsp in the loop. Encoded as copying the live-in $rax value in block 1
1243   // to $rsp.
1244   TransferFunc[0].insert({RaxLoc, LiveInRsp});
1245   TransferFunc[1].insert({RspLoc, RaxPHIInBlk1});
1246   initValueArray(InLocsPtr, 3, 2);
1247   initValueArray(OutLocsPtr, 3, 2);
1248   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1249   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1250   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1251   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1252   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1253   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1254   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1255   // Check $rax's values.
1256   EXPECT_EQ(InLocs[0][1], LiveInRax);
1257   EXPECT_EQ(InLocs[1][1], LiveInRsp);
1258   EXPECT_EQ(InLocs[2][1], LiveInRsp);
1259   EXPECT_EQ(OutLocs[0][1], LiveInRsp);
1260   EXPECT_EQ(OutLocs[1][1], LiveInRsp);
1261   EXPECT_EQ(OutLocs[2][1], LiveInRsp);
1262   TransferFunc[0].clear();
1263   TransferFunc[1].clear();
1264 }
1265 
1266 TEST_F(InstrRefLDVTest, MLocNestedLoop) {
1267   //    entry
1268   //     |
1269   //    loop1
1270   //     ^\
1271   //     | \    /-\
1272   //     |  loop2  |
1273   //     |  /   \-/
1274   //     ^ /
1275   //     join
1276   //     |
1277   //     ret
1278   setupNestedLoops();
1279 
1280   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1281   LocIdx RspLoc(0);
1282   Register RAX = getRegByName("RAX");
1283   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1284 
1285   ValueIDNum InLocs[5][2], OutLocs[5][2];
1286   ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3],
1287                               InLocs[4]};
1288   ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3],
1289                                OutLocs[4]};
1290 
1291   SmallVector<MLocTransferMap, 1> TransferFunc;
1292   TransferFunc.resize(5);
1293 
1294   unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2, JoinBlk = 3;
1295 
1296   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1297   ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc);
1298   ValueIDNum RspDefInBlk1(Loop1Blk, 1, RspLoc);
1299   ValueIDNum RspPHIInBlk2(Loop2Blk, 0, RspLoc);
1300   ValueIDNum RspDefInBlk2(Loop2Blk, 1, RspLoc);
1301   ValueIDNum RspDefInBlk3(JoinBlk, 1, RspLoc);
1302   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
1303   ValueIDNum RaxPHIInBlk1(Loop1Blk, 0, RaxLoc);
1304   ValueIDNum RaxPHIInBlk2(Loop2Blk, 0, RaxLoc);
1305 
1306   // Like the other tests: first ensure that if there's nothing in the transfer
1307   // function, then everything is live-through (check $rsp).
1308   initValueArray(InLocsPtr, 5, 2);
1309   initValueArray(OutLocsPtr, 5, 2);
1310   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1311   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1312   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1313   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1314   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1315   EXPECT_EQ(InLocs[4][0], LiveInRsp);
1316   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1317   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1318   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1319   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1320   EXPECT_EQ(OutLocs[4][0], LiveInRsp);
1321 
1322   // A def in the inner loop means we should get PHIs at the heads of both
1323   // loops. Live-outs of the last three blocks will be the def, as it dominates
1324   // those.
1325   TransferFunc[2].insert({RspLoc, RspDefInBlk2});
1326   initValueArray(InLocsPtr, 5, 2);
1327   initValueArray(OutLocsPtr, 5, 2);
1328   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1329   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1330   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1331   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1332   EXPECT_EQ(InLocs[3][0], RspDefInBlk2);
1333   EXPECT_EQ(InLocs[4][0], RspDefInBlk2);
1334   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1335   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1336   EXPECT_EQ(OutLocs[2][0], RspDefInBlk2);
1337   EXPECT_EQ(OutLocs[3][0], RspDefInBlk2);
1338   EXPECT_EQ(OutLocs[4][0], RspDefInBlk2);
1339   TransferFunc[2].clear();
1340 
1341   // Adding a def to the outer loop header shouldn't affect this much -- the
1342   // live-out of block 1 changes.
1343   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1344   TransferFunc[2].insert({RspLoc, RspDefInBlk2});
1345   initValueArray(InLocsPtr, 5, 2);
1346   initValueArray(OutLocsPtr, 5, 2);
1347   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1348   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1349   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1350   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1351   EXPECT_EQ(InLocs[3][0], RspDefInBlk2);
1352   EXPECT_EQ(InLocs[4][0], RspDefInBlk2);
1353   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1354   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1355   EXPECT_EQ(OutLocs[2][0], RspDefInBlk2);
1356   EXPECT_EQ(OutLocs[3][0], RspDefInBlk2);
1357   EXPECT_EQ(OutLocs[4][0], RspDefInBlk2);
1358   TransferFunc[1].clear();
1359   TransferFunc[2].clear();
1360 
1361   // Likewise, putting a def in the outer loop tail shouldn't affect where
1362   // the PHIs go, and should propagate into the ret block.
1363 
1364   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1365   TransferFunc[2].insert({RspLoc, RspDefInBlk2});
1366   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1367   initValueArray(InLocsPtr, 5, 2);
1368   initValueArray(OutLocsPtr, 5, 2);
1369   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1370   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1371   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1372   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1373   EXPECT_EQ(InLocs[3][0], RspDefInBlk2);
1374   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1375   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1376   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1377   EXPECT_EQ(OutLocs[2][0], RspDefInBlk2);
1378   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1379   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1380   TransferFunc[1].clear();
1381   TransferFunc[2].clear();
1382   TransferFunc[3].clear();
1383 
1384   // However: if we don't def in the inner-loop, then we just have defs in the
1385   // head and tail of the outer loop. The inner loop should be live-through.
1386   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1387   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1388   initValueArray(InLocsPtr, 5, 2);
1389   initValueArray(OutLocsPtr, 5, 2);
1390   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1391   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1392   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1393   EXPECT_EQ(InLocs[2][0], RspDefInBlk1);
1394   EXPECT_EQ(InLocs[3][0], RspDefInBlk1);
1395   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1396   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1397   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1398   EXPECT_EQ(OutLocs[2][0], RspDefInBlk1);
1399   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1400   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1401   TransferFunc[1].clear();
1402   TransferFunc[3].clear();
1403 
1404   // Check that this still works if we copy RspDefInBlk1 to $rax and then
1405   // copy it back into $rsp in the inner loop.
1406   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1407   TransferFunc[1].insert({RaxLoc, RspDefInBlk1});
1408   TransferFunc[2].insert({RspLoc, RaxPHIInBlk2});
1409   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1410   initValueArray(InLocsPtr, 5, 2);
1411   initValueArray(OutLocsPtr, 5, 2);
1412   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1413   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1414   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1415   EXPECT_EQ(InLocs[2][0], RspDefInBlk1);
1416   EXPECT_EQ(InLocs[3][0], RspDefInBlk1);
1417   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1418   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1419   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1420   EXPECT_EQ(OutLocs[2][0], RspDefInBlk1);
1421   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1422   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1423   // Look at raxes value in the relevant blocks,
1424   EXPECT_EQ(InLocs[2][1], RspDefInBlk1);
1425   EXPECT_EQ(OutLocs[1][1], RspDefInBlk1);
1426   TransferFunc[1].clear();
1427   TransferFunc[2].clear();
1428   TransferFunc[3].clear();
1429 
1430   // If we have a single def in the tail of the outer loop, that should produce
1431   // a PHI at the loop head, and be live-through the inner loop.
1432   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1433   initValueArray(InLocsPtr, 5, 2);
1434   initValueArray(OutLocsPtr, 5, 2);
1435   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1436   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1437   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1438   EXPECT_EQ(InLocs[2][0], RspPHIInBlk1);
1439   EXPECT_EQ(InLocs[3][0], RspPHIInBlk1);
1440   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1441   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1442   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1443   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk1);
1444   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1445   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1446   TransferFunc[3].clear();
1447 
1448   // And if we copy from $rsp to $rax in block 2, it should resolve to the PHI
1449   // in block 1, and we should keep that value in rax until the ret block.
1450   // There'll be a PHI in block 1 and 2, because we're putting a def in the
1451   // inner loop.
1452   TransferFunc[2].insert({RaxLoc, RspPHIInBlk2});
1453   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1454   initValueArray(InLocsPtr, 5, 2);
1455   initValueArray(OutLocsPtr, 5, 2);
1456   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1457   // Examining the values of rax,
1458   EXPECT_EQ(InLocs[0][1], LiveInRax);
1459   EXPECT_EQ(InLocs[1][1], RaxPHIInBlk1);
1460   EXPECT_EQ(InLocs[2][1], RaxPHIInBlk2);
1461   EXPECT_EQ(InLocs[3][1], RspPHIInBlk1);
1462   EXPECT_EQ(InLocs[4][1], RspPHIInBlk1);
1463   EXPECT_EQ(OutLocs[0][1], LiveInRax);
1464   EXPECT_EQ(OutLocs[1][1], RaxPHIInBlk1);
1465   EXPECT_EQ(OutLocs[2][1], RspPHIInBlk1);
1466   EXPECT_EQ(OutLocs[3][1], RspPHIInBlk1);
1467   EXPECT_EQ(OutLocs[4][1], RspPHIInBlk1);
1468   TransferFunc[2].clear();
1469   TransferFunc[3].clear();
1470 }
1471 
1472 TEST_F(InstrRefLDVTest, MLocNoDominatingLoop) {
1473   //           entry
1474   //            / \
1475   //           /   \
1476   //          /     \
1477   //        head1   head2
1478   //        ^  \   /   ^
1479   //        ^   \ /    ^
1480   //        \-joinblk -/
1481   //             |
1482   //            ret
1483   setupNoDominatingLoop();
1484 
1485   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1486   LocIdx RspLoc(0);
1487   Register RAX = getRegByName("RAX");
1488   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1489 
1490   ValueIDNum InLocs[5][2], OutLocs[5][2];
1491   ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3],
1492                               InLocs[4]};
1493   ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3],
1494                                OutLocs[4]};
1495 
1496   SmallVector<MLocTransferMap, 1> TransferFunc;
1497   TransferFunc.resize(5);
1498 
1499   unsigned EntryBlk = 0, Head1Blk = 1, Head2Blk = 2, JoinBlk = 3;
1500 
1501   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1502   ValueIDNum RspPHIInBlk1(Head1Blk, 0, RspLoc);
1503   ValueIDNum RspDefInBlk1(Head1Blk, 1, RspLoc);
1504   ValueIDNum RspPHIInBlk2(Head2Blk, 0, RspLoc);
1505   ValueIDNum RspDefInBlk2(Head2Blk, 1, RspLoc);
1506   ValueIDNum RspPHIInBlk3(JoinBlk, 0, RspLoc);
1507   ValueIDNum RspDefInBlk3(JoinBlk, 1, RspLoc);
1508   ValueIDNum RaxPHIInBlk1(Head1Blk, 0, RaxLoc);
1509   ValueIDNum RaxPHIInBlk2(Head2Blk, 0, RaxLoc);
1510 
1511   // As ever, test that everything is live-through if there are no defs.
1512   initValueArray(InLocsPtr, 5, 2);
1513   initValueArray(OutLocsPtr, 5, 2);
1514   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1515   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1516   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1517   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1518   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1519   EXPECT_EQ(InLocs[4][0], LiveInRsp);
1520   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1521   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1522   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1523   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1524   EXPECT_EQ(OutLocs[4][0], LiveInRsp);
1525 
1526   // Putting a def in the 'join' block will cause us to have two distinct
1527   // PHIs in each loop head, then on entry to the join block.
1528   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1529   initValueArray(InLocsPtr, 5, 2);
1530   initValueArray(OutLocsPtr, 5, 2);
1531   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1532   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1533   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1534   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1535   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1536   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1537   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1538   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1539   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2);
1540   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1541   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1542   TransferFunc[3].clear();
1543 
1544   // We should get the same behaviour if we put the def in either of the
1545   // loop heads -- it should force the other head to be a PHI.
1546   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1547   initValueArray(InLocsPtr, 5, 2);
1548   initValueArray(OutLocsPtr, 5, 2);
1549   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1550   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1551   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1552   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1553   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1554   EXPECT_EQ(InLocs[4][0], RspPHIInBlk3);
1555   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1556   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1557   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2);
1558   EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3);
1559   EXPECT_EQ(OutLocs[4][0], RspPHIInBlk3);
1560   TransferFunc[1].clear();
1561 
1562   // Check symmetry,
1563   TransferFunc[2].insert({RspLoc, RspDefInBlk2});
1564   initValueArray(InLocsPtr, 5, 2);
1565   initValueArray(OutLocsPtr, 5, 2);
1566   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1567   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1568   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1569   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1570   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1571   EXPECT_EQ(InLocs[4][0], RspPHIInBlk3);
1572   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1573   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1574   EXPECT_EQ(OutLocs[2][0], RspDefInBlk2);
1575   EXPECT_EQ(OutLocs[3][0], RspPHIInBlk3);
1576   EXPECT_EQ(OutLocs[4][0], RspPHIInBlk3);
1577   TransferFunc[2].clear();
1578 
1579   // Test some scenarios where there _shouldn't_ be any PHIs created at heads.
1580   // These are those PHIs are created, but value propagation eliminates them.
1581   // For example, lets copy rsp-livein to $rsp inside each loop head, so that
1582   // there's no need for a PHI in the join block. Put a def of $rsp in block 3
1583   // to force PHIs elsewhere.
1584   TransferFunc[0].insert({RaxLoc, LiveInRsp});
1585   TransferFunc[1].insert({RspLoc, RaxPHIInBlk1});
1586   TransferFunc[2].insert({RspLoc, RaxPHIInBlk2});
1587   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1588   initValueArray(InLocsPtr, 5, 2);
1589   initValueArray(OutLocsPtr, 5, 2);
1590   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1591   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1592   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1593   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1594   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1595   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1596   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1597   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1598   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1599   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1600   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1601   TransferFunc[0].clear();
1602   TransferFunc[1].clear();
1603   TransferFunc[2].clear();
1604   TransferFunc[3].clear();
1605 
1606   // In fact, if we eliminate the def in block 3, none of those PHIs are
1607   // necessary, as we're just repeatedly copying LiveInRsp into $rsp. They
1608   // should all be value propagated out.
1609   TransferFunc[0].insert({RaxLoc, LiveInRsp});
1610   TransferFunc[1].insert({RspLoc, RaxPHIInBlk1});
1611   TransferFunc[2].insert({RspLoc, RaxPHIInBlk2});
1612   initValueArray(InLocsPtr, 5, 2);
1613   initValueArray(OutLocsPtr, 5, 2);
1614   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1615   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1616   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1617   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1618   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1619   EXPECT_EQ(InLocs[4][0], LiveInRsp);
1620   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1621   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1622   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1623   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1624   EXPECT_EQ(OutLocs[4][0], LiveInRsp);
1625   TransferFunc[0].clear();
1626   TransferFunc[1].clear();
1627   TransferFunc[2].clear();
1628 }
1629 
1630 TEST_F(InstrRefLDVTest, MLocBadlyNestedLoops) {
1631   //           entry
1632   //             |
1633   //           loop1 -o
1634   //             | ^
1635   //             | ^
1636   //           loop2 -o
1637   //             | ^
1638   //             | ^
1639   //           loop3 -o
1640   //             |
1641   //            ret
1642   setupBadlyNestedLoops();
1643 
1644   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1645   LocIdx RspLoc(0);
1646   Register RAX = getRegByName("RAX");
1647   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1648 
1649   ValueIDNum InLocs[5][2], OutLocs[5][2];
1650   ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3],
1651                               InLocs[4]};
1652   ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3],
1653                                OutLocs[4]};
1654 
1655   SmallVector<MLocTransferMap, 1> TransferFunc;
1656   TransferFunc.resize(5);
1657 
1658   unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2, Loop3Blk = 3;
1659 
1660   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1661   ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc);
1662   ValueIDNum RspDefInBlk1(Loop1Blk, 1, RspLoc);
1663   ValueIDNum RspPHIInBlk2(Loop2Blk, 0, RspLoc);
1664   ValueIDNum RspPHIInBlk3(Loop3Blk, 0, RspLoc);
1665   ValueIDNum RspDefInBlk3(Loop3Blk, 1, RspLoc);
1666   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
1667   ValueIDNum RaxPHIInBlk3(Loop3Blk, 0, RaxLoc);
1668 
1669   // As ever, test that everything is live-through if there are no defs.
1670   initValueArray(InLocsPtr, 5, 2);
1671   initValueArray(OutLocsPtr, 5, 2);
1672   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1673   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1674   EXPECT_EQ(InLocs[1][0], LiveInRsp);
1675   EXPECT_EQ(InLocs[2][0], LiveInRsp);
1676   EXPECT_EQ(InLocs[3][0], LiveInRsp);
1677   EXPECT_EQ(InLocs[4][0], LiveInRsp);
1678   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1679   EXPECT_EQ(OutLocs[1][0], LiveInRsp);
1680   EXPECT_EQ(OutLocs[2][0], LiveInRsp);
1681   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1682   EXPECT_EQ(OutLocs[4][0], LiveInRsp);
1683 
1684   // A def in loop3 should cause PHIs in every loop block: they're all
1685   // reachable from each other.
1686   TransferFunc[3].insert({RspLoc, RspDefInBlk3});
1687   initValueArray(InLocsPtr, 5, 2);
1688   initValueArray(OutLocsPtr, 5, 2);
1689   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1690   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1691   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1692   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1693   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1694   EXPECT_EQ(InLocs[4][0], RspDefInBlk3);
1695   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1696   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1697   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2);
1698   EXPECT_EQ(OutLocs[3][0], RspDefInBlk3);
1699   EXPECT_EQ(OutLocs[4][0], RspDefInBlk3);
1700   TransferFunc[3].clear();
1701 
1702   // A def in loop1 should cause a PHI in loop1, but not the other blocks.
1703   // loop2 and loop3 are dominated by the def in loop1, so they should have
1704   // that value live-through.
1705   TransferFunc[1].insert({RspLoc, RspDefInBlk1});
1706   initValueArray(InLocsPtr, 5, 2);
1707   initValueArray(OutLocsPtr, 5, 2);
1708   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1709   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1710   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1711   EXPECT_EQ(InLocs[2][0], RspDefInBlk1);
1712   EXPECT_EQ(InLocs[3][0], RspDefInBlk1);
1713   EXPECT_EQ(InLocs[4][0], RspDefInBlk1);
1714   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1715   EXPECT_EQ(OutLocs[1][0], RspDefInBlk1);
1716   EXPECT_EQ(OutLocs[2][0], RspDefInBlk1);
1717   EXPECT_EQ(OutLocs[3][0], RspDefInBlk1);
1718   EXPECT_EQ(OutLocs[4][0], RspDefInBlk1);
1719   TransferFunc[1].clear();
1720 
1721   // As with earlier tricks: copy $rsp to $rax in the entry block, then $rax
1722   // to $rsp in block 3. The only def of $rsp is simply copying the same value
1723   // back into itself, and the value of $rsp is LiveInRsp all the way through.
1724   // PHIs should be created, then value-propagated away...  however this
1725   // doesn't work in practice.
1726   // Consider the entry to loop3: we can determine that there's an incoming
1727   // PHI value from loop2, and LiveInRsp from the self-loop. This would still
1728   // justify having a PHI on entry to loop3. The only way to completely
1729   // value-propagate these PHIs away would be to speculatively explore what
1730   // PHIs could be eliminated and what that would lead to; which is
1731   // combinatorially complex.
1732   // Happily:
1733   //  a) In this scenario, we always have a tracked location for LiveInRsp
1734   //     anyway, so there's no loss in availability,
1735   //  b) Only DBG_PHIs of a register would be vunlerable to this scenario, and
1736   //     even then only if a true PHI became a DBG_PHI and was then optimised
1737   //     through branch folding to no longer be at a CFG join,
1738   //  c) The register allocator can spot this kind of redundant COPY easily,
1739   //     and eliminate it.
1740   //
1741   // This unit test left in as a reference for the limitations of this
1742   // approach. PHIs will be left in $rsp on entry to each block.
1743   TransferFunc[0].insert({RaxLoc, LiveInRsp});
1744   TransferFunc[3].insert({RspLoc, RaxPHIInBlk3});
1745   initValueArray(InLocsPtr, 5, 2);
1746   initValueArray(OutLocsPtr, 5, 2);
1747   buildMLocValueMap(InLocsPtr, OutLocsPtr, TransferFunc);
1748   EXPECT_EQ(InLocs[0][0], LiveInRsp);
1749   EXPECT_EQ(InLocs[1][0], RspPHIInBlk1);
1750   EXPECT_EQ(InLocs[2][0], RspPHIInBlk2);
1751   EXPECT_EQ(InLocs[3][0], RspPHIInBlk3);
1752   EXPECT_EQ(InLocs[4][0], LiveInRsp);
1753   EXPECT_EQ(OutLocs[0][0], LiveInRsp);
1754   EXPECT_EQ(OutLocs[1][0], RspPHIInBlk1);
1755   EXPECT_EQ(OutLocs[2][0], RspPHIInBlk2);
1756   EXPECT_EQ(OutLocs[3][0], LiveInRsp);
1757   EXPECT_EQ(OutLocs[4][0], LiveInRsp);
1758   // Check $rax's value. It should have $rsps value from the entry block
1759   // onwards.
1760   EXPECT_EQ(InLocs[0][1], LiveInRax);
1761   EXPECT_EQ(InLocs[1][1], LiveInRsp);
1762   EXPECT_EQ(InLocs[2][1], LiveInRsp);
1763   EXPECT_EQ(InLocs[3][1], LiveInRsp);
1764   EXPECT_EQ(InLocs[4][1], LiveInRsp);
1765   EXPECT_EQ(OutLocs[0][1], LiveInRsp);
1766   EXPECT_EQ(OutLocs[1][1], LiveInRsp);
1767   EXPECT_EQ(OutLocs[2][1], LiveInRsp);
1768   EXPECT_EQ(OutLocs[3][1], LiveInRsp);
1769   EXPECT_EQ(OutLocs[4][1], LiveInRsp);
1770 }
1771 
1772 TEST_F(InstrRefLDVTest, pickVPHILocDiamond) {
1773   //        entry
1774   //        /  \
1775   //      br1  br2
1776   //        \  /
1777   //         ret
1778   setupDiamondBlocks();
1779 
1780   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1781   LocIdx RspLoc(0);
1782   Register RAX = getRegByName("RAX");
1783   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1784 
1785   ValueIDNum OutLocs[4][2];
1786   ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]};
1787 
1788   initValueArray(OutLocsPtr, 4, 2);
1789 
1790   unsigned EntryBlk = 0, Br2Blk = 2, RetBlk = 3;
1791 
1792   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1793   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
1794   ValueIDNum RspPHIInBlk2(Br2Blk, 0, RspLoc);
1795   ValueIDNum RspPHIInBlk3(RetBlk, 0, RspLoc);
1796 
1797   DebugVariable Var(FuncVariable, None, nullptr);
1798   DbgValueProperties EmptyProps(EmptyExpr, false);
1799   SmallVector<DbgValue, 32> VLiveOuts;
1800   VLiveOuts.resize(4, DbgValue(EmptyProps, DbgValue::Undef));
1801   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
1802   VLiveOutIdx[MBB0] = &VLiveOuts[0];
1803   VLiveOutIdx[MBB1] = &VLiveOuts[1];
1804   VLiveOutIdx[MBB2] = &VLiveOuts[2];
1805   VLiveOutIdx[MBB3] = &VLiveOuts[3];
1806 
1807   SmallVector<const MachineBasicBlock *, 2> Preds;
1808   for (const auto *Pred : MBB3->predecessors())
1809     Preds.push_back(Pred);
1810 
1811   // Specify the live-outs around the joining block.
1812   OutLocs[1][0] = LiveInRsp;
1813   OutLocs[2][0] = LiveInRax;
1814 
1815   Optional<ValueIDNum> Result;
1816 
1817   // Simple case: join two distinct values on entry to the block.
1818   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1819   VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
1820   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1821   // Should have picked a PHI in $rsp in block 3.
1822   EXPECT_TRUE(Result);
1823   if (Result) {
1824     EXPECT_EQ(*Result, RspPHIInBlk3);
1825   }
1826 
1827   // If the incoming values are swapped between blocks, we should not
1828   // successfully join. The CFG merge would select the right values, but in
1829   // the wrong conditions.
1830   std::swap(VLiveOuts[1], VLiveOuts[2]);
1831   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1832   EXPECT_FALSE(Result);
1833 
1834   // Swap back,
1835   std::swap(VLiveOuts[1], VLiveOuts[2]);
1836   // Setting one of these to being a constant should prohibit merging.
1837   VLiveOuts[1].Kind = DbgValue::Const;
1838   VLiveOuts[1].MO = MachineOperand::CreateImm(0);
1839   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1840   EXPECT_FALSE(Result);
1841 
1842   // Seeing both to being a constant -> still prohibit, it shouldn't become
1843   // a value in the register file anywhere.
1844   VLiveOuts[2] = VLiveOuts[1];
1845   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1846   EXPECT_FALSE(Result);
1847 
1848   // NoVals shouldn't join with anything else.
1849   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1850   VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::NoVal);
1851   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1852   EXPECT_FALSE(Result);
1853 
1854   // We might merge in another VPHI in such a join. Present pickVPHILoc with
1855   // such a scenario: first, where one incoming edge has a VPHI with no known
1856   // value. This represents an edge where there was a PHI value that can't be
1857   // found in the register file -- we can't subsequently find a PHI here.
1858   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1859   VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI);
1860   EXPECT_EQ(VLiveOuts[2].ID, ValueIDNum::EmptyValue);
1861   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1862   EXPECT_FALSE(Result);
1863 
1864   // However, if we know the value of the incoming VPHI, we can search for its
1865   // location. Use a PHI machine-value for doing this, as VPHIs should always
1866   // have PHI values, or they should have been eliminated.
1867   OutLocs[2][0] = RspPHIInBlk2;
1868   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1869   VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI);
1870   VLiveOuts[2].ID = RspPHIInBlk2; // Set location where PHI happens.
1871   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1872   EXPECT_TRUE(Result);
1873   if (Result) {
1874     EXPECT_EQ(*Result, RspPHIInBlk3);
1875   }
1876 
1877   // If that value isn't available from that block, don't join.
1878   OutLocs[2][0] = LiveInRsp;
1879   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1880   EXPECT_FALSE(Result);
1881 
1882   // Check that we don't pick values when the properties disagree, for example
1883   // different indirectness or DIExpression.
1884   DIExpression *NewExpr =
1885       DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4);
1886   DbgValueProperties PropsWithExpr(NewExpr, false);
1887   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1888   VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithExpr, DbgValue::Def);
1889   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1890   EXPECT_FALSE(Result);
1891 
1892   DbgValueProperties PropsWithIndirect(EmptyExpr, true);
1893   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1894   VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def);
1895   Result = pickVPHILoc(*MBB3, Var, VLiveOutIdx, OutLocsPtr, Preds);
1896   EXPECT_FALSE(Result);
1897 }
1898 
1899 TEST_F(InstrRefLDVTest, pickVPHILocLoops) {
1900   setupSimpleLoop();
1901   //    entry
1902   //     |
1903   //     |/-----\
1904   //    loopblk |
1905   //     |\-----/
1906   //     |
1907   //     ret
1908 
1909   ASSERT_TRUE(MTracker->getNumLocs() == 1);
1910   LocIdx RspLoc(0);
1911   Register RAX = getRegByName("RAX");
1912   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
1913 
1914   ValueIDNum OutLocs[3][2];
1915   ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2]};
1916 
1917   initValueArray(OutLocsPtr, 3, 2);
1918 
1919   unsigned EntryBlk = 0, LoopBlk = 1;
1920 
1921   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
1922   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
1923   ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc);
1924   ValueIDNum RaxPHIInBlk1(LoopBlk, 0, RaxLoc);
1925 
1926   DebugVariable Var(FuncVariable, None, nullptr);
1927   DbgValueProperties EmptyProps(EmptyExpr, false);
1928   SmallVector<DbgValue, 32> VLiveOuts;
1929   VLiveOuts.resize(3, DbgValue(EmptyProps, DbgValue::Undef));
1930   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
1931   VLiveOutIdx[MBB0] = &VLiveOuts[0];
1932   VLiveOutIdx[MBB1] = &VLiveOuts[1];
1933   VLiveOutIdx[MBB2] = &VLiveOuts[2];
1934 
1935   SmallVector<const MachineBasicBlock *, 2> Preds;
1936   for (const auto *Pred : MBB1->predecessors())
1937     Preds.push_back(Pred);
1938 
1939   // Specify the live-outs around the joining block.
1940   OutLocs[0][0] = LiveInRsp;
1941   OutLocs[1][0] = LiveInRax;
1942 
1943   Optional<ValueIDNum> Result;
1944 
1945   // See that we can merge as normal on a backedge.
1946   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1947   VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
1948   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
1949   // Should have picked a PHI in $rsp in block 1.
1950   EXPECT_TRUE(Result);
1951   if (Result) {
1952     EXPECT_EQ(*Result, RspPHIInBlk1);
1953   }
1954 
1955   // And that, if the desired values aren't available, we don't merge.
1956   OutLocs[1][0] = LiveInRsp;
1957   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
1958   EXPECT_FALSE(Result);
1959 
1960   // Test the backedge behaviour: PHIs that feed back into themselves can
1961   // carry this variables value. Feed in LiveInRsp in both $rsp and $rax
1962   // from the entry block, but only put an appropriate backedge PHI in $rax.
1963   // Only the $rax location can form the correct PHI.
1964   OutLocs[0][0] = LiveInRsp;
1965   OutLocs[0][1] = LiveInRsp;
1966   OutLocs[1][0] = RaxPHIInBlk1;
1967   OutLocs[1][1] = RaxPHIInBlk1;
1968   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1969   // Crucially, a VPHI originating in this block:
1970   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
1971   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
1972   EXPECT_TRUE(Result);
1973   if (Result) {
1974     EXPECT_EQ(*Result, RaxPHIInBlk1);
1975   }
1976 
1977   // Merging should not be permitted if there's a usable PHI on the backedge,
1978   // but it's in the wrong place. (Overwrite $rax).
1979   OutLocs[1][1] = LiveInRax;
1980   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
1981   EXPECT_FALSE(Result);
1982 
1983   // Additionally, if the VPHI coming back on the loop backedge isn't from
1984   // this block (block 1), we can't merge it.
1985   OutLocs[1][1] = RaxPHIInBlk1;
1986   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
1987   VLiveOuts[1] = DbgValue(0, EmptyProps, DbgValue::VPHI);
1988   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
1989   EXPECT_FALSE(Result);
1990 }
1991 
1992 TEST_F(InstrRefLDVTest, pickVPHILocBadlyNestedLoops) {
1993   // Run some tests similar to pickVPHILocLoops, with more than one backedge,
1994   // and check that we merge correctly over many candidate locations.
1995   setupBadlyNestedLoops();
1996   //           entry
1997   //             |
1998   //           loop1 -o
1999   //             | ^
2000   //             | ^
2001   //           loop2 -o
2002   //             | ^
2003   //             | ^
2004   //           loop3 -o
2005   //             |
2006   //            ret
2007   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2008   LocIdx RspLoc(0);
2009   Register RAX = getRegByName("RAX");
2010   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2011   Register RBX = getRegByName("RBX");
2012   LocIdx RbxLoc = MTracker->lookupOrTrackRegister(RBX);
2013 
2014   ValueIDNum OutLocs[5][3];
2015   ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]};
2016 
2017   initValueArray(OutLocsPtr, 5, 3);
2018 
2019   unsigned EntryBlk = 0, Loop1Blk = 1;
2020 
2021   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
2022   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
2023   ValueIDNum LiveInRbx(EntryBlk, 0, RbxLoc);
2024   ValueIDNum RspPHIInBlk1(Loop1Blk, 0, RspLoc);
2025   ValueIDNum RaxPHIInBlk1(Loop1Blk, 0, RaxLoc);
2026   ValueIDNum RbxPHIInBlk1(Loop1Blk, 0, RbxLoc);
2027 
2028   DebugVariable Var(FuncVariable, None, nullptr);
2029   DbgValueProperties EmptyProps(EmptyExpr, false);
2030   SmallVector<DbgValue, 32> VLiveOuts;
2031   VLiveOuts.resize(5, DbgValue(EmptyProps, DbgValue::Undef));
2032   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
2033   VLiveOutIdx[MBB0] = &VLiveOuts[0];
2034   VLiveOutIdx[MBB1] = &VLiveOuts[1];
2035   VLiveOutIdx[MBB2] = &VLiveOuts[2];
2036   VLiveOutIdx[MBB3] = &VLiveOuts[3];
2037   VLiveOutIdx[MBB4] = &VLiveOuts[4];
2038 
2039   // We're going to focus on block 1.
2040   SmallVector<const MachineBasicBlock *, 2> Preds;
2041   for (const auto *Pred : MBB1->predecessors())
2042     Preds.push_back(Pred);
2043 
2044   // Specify the live-outs around the joining block. Incoming edges from the
2045   // entry block, self, and loop2.
2046   OutLocs[0][0] = LiveInRsp;
2047   OutLocs[1][0] = LiveInRax;
2048   OutLocs[2][0] = LiveInRbx;
2049 
2050   Optional<ValueIDNum> Result;
2051 
2052   // See that we can merge as normal on a backedge.
2053   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2054   VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2055   VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def);
2056   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2057   // Should have picked a PHI in $rsp in block 1.
2058   EXPECT_TRUE(Result);
2059   if (Result) {
2060     EXPECT_EQ(*Result, RspPHIInBlk1);
2061   }
2062 
2063   // Check too that permuting the live-out locations prevents merging
2064   OutLocs[0][0] = LiveInRax;
2065   OutLocs[1][0] = LiveInRbx;
2066   OutLocs[2][0] = LiveInRsp;
2067   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2068   EXPECT_FALSE(Result);
2069 
2070   OutLocs[0][0] = LiveInRsp;
2071   OutLocs[1][0] = LiveInRax;
2072   OutLocs[2][0] = LiveInRbx;
2073 
2074   // Feeding a PHI back on one backedge shouldn't merge (block 1 self backedge
2075   // wants LiveInRax).
2076   OutLocs[1][0] = RspPHIInBlk1;
2077   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2078   EXPECT_FALSE(Result);
2079 
2080   // If the variables value on that edge is a VPHI feeding into itself, that's
2081   // fine.
2082   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2083   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2084   VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def);
2085   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2086   EXPECT_TRUE(Result);
2087   if (Result) {
2088     EXPECT_EQ(*Result, RspPHIInBlk1);
2089   }
2090 
2091   // Likewise: the other backedge being a VPHI from block 1 should be accepted.
2092   OutLocs[2][0] = RspPHIInBlk1;
2093   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2094   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2095   VLiveOuts[2] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2096   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2097   EXPECT_TRUE(Result);
2098   if (Result) {
2099     EXPECT_EQ(*Result, RspPHIInBlk1);
2100   }
2101 
2102   // Here's where it becomes tricky: we should not merge if there are two
2103   // _distinct_ backedge PHIs. We can't have a PHI that happens in both rsp
2104   // and rax for example. We can only pick one location as the live-in.
2105   OutLocs[2][0] = RaxPHIInBlk1;
2106   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2107   EXPECT_FALSE(Result);
2108 
2109   // The above test sources correct machine-PHI-value from two places. Now
2110   // try with one machine-PHI-value, but placed in two different locations
2111   // on the backedge. Again, we can't merge a location here, there's no
2112   // location that works on all paths.
2113   OutLocs[0][0] = LiveInRsp;
2114   OutLocs[1][0] = RspPHIInBlk1;
2115   OutLocs[2][0] = LiveInRsp;
2116   OutLocs[2][1] = RspPHIInBlk1;
2117   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2118   EXPECT_FALSE(Result);
2119 
2120   // Scatter various PHI values across the available locations. Only rbx (loc 2)
2121   // has the right value in both backedges -- that's the loc that should be
2122   // picked.
2123   OutLocs[0][2] = LiveInRsp;
2124   OutLocs[1][0] = RspPHIInBlk1;
2125   OutLocs[1][1] = RaxPHIInBlk1;
2126   OutLocs[1][2] = RbxPHIInBlk1;
2127   OutLocs[2][0] = LiveInRsp;
2128   OutLocs[2][1] = RspPHIInBlk1;
2129   OutLocs[2][2] = RbxPHIInBlk1;
2130   Result = pickVPHILoc(*MBB1, Var, VLiveOutIdx, OutLocsPtr, Preds);
2131   EXPECT_TRUE(Result);
2132   if (Result) {
2133     EXPECT_EQ(*Result, RbxPHIInBlk1);
2134   }
2135 }
2136 
2137 TEST_F(InstrRefLDVTest, vlocJoinDiamond) {
2138   //        entry
2139   //        /  \
2140   //      br1  br2
2141   //        \  /
2142   //         ret
2143   setupDiamondBlocks();
2144 
2145   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2146   LocIdx RspLoc(0);
2147   Register RAX = getRegByName("RAX");
2148   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2149 
2150   unsigned EntryBlk = 0, Br2Blk = 2, RetBlk = 3;
2151 
2152   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
2153   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
2154   ValueIDNum RspPHIInBlkBr2Blk(Br2Blk, 0, RspLoc);
2155   ValueIDNum RspPHIInBlkRetBlk(RetBlk, 0, RspLoc);
2156 
2157   DebugVariable Var(FuncVariable, None, nullptr);
2158   DbgValueProperties EmptyProps(EmptyExpr, false);
2159   SmallVector<DbgValue, 32> VLiveOuts;
2160   VLiveOuts.resize(4, DbgValue(EmptyProps, DbgValue::Undef));
2161   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
2162   VLiveOutIdx[MBB0] = &VLiveOuts[0];
2163   VLiveOutIdx[MBB1] = &VLiveOuts[1];
2164   VLiveOutIdx[MBB2] = &VLiveOuts[2];
2165   VLiveOutIdx[MBB3] = &VLiveOuts[3];
2166 
2167   SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks;
2168   AllBlocks.insert(MBB0);
2169   AllBlocks.insert(MBB1);
2170   AllBlocks.insert(MBB2);
2171   AllBlocks.insert(MBB3);
2172 
2173   SmallVector<const MachineBasicBlock *, 2> Preds;
2174   for (const auto *Pred : MBB3->predecessors())
2175     Preds.push_back(Pred);
2176 
2177   SmallSet<DebugVariable, 4> AllVars;
2178   AllVars.insert(Var);
2179 
2180   // vlocJoin is here to propagate incoming values, and eliminate PHIs. Start
2181   // off by propagating a value into the merging block, number 3.
2182   DbgValue JoinedLoc = DbgValue(3, EmptyProps, DbgValue::NoVal);
2183   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2184   VLiveOuts[2] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2185   bool Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2186   EXPECT_TRUE(Result); // Output locs should have changed.
2187   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2188   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2189 
2190   // And if we did it a second time, leaving the live-ins as it was, then
2191   // we should report no change.
2192   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2193   EXPECT_FALSE(Result);
2194 
2195   // If the live-in variable values are different, but there's no PHI placed
2196   // in this block, then just pick a location. It should be the first (in RPO)
2197   // predecessor to avoid being a backedge.
2198   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2199   VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2200   JoinedLoc = DbgValue(3, EmptyProps, DbgValue::NoVal);
2201   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2202   EXPECT_TRUE(Result);
2203   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2204   // RPO is blocks 0 2 1 3, so LiveInRax is picked as the first predecessor
2205   // of this join.
2206   EXPECT_EQ(JoinedLoc.ID, LiveInRax);
2207 
2208   // No tests for whether vlocJoin will pass-through a variable with differing
2209   // expressions / properties. Those can only come about due to assignments; and
2210   // for any assignment at all, a PHI should have been placed at the dominance
2211   // frontier. We rely on the IDF calculator being accurate (which is OK,
2212   // because so does the rest of LLVM).
2213 
2214   // Try placing a PHI. With differing input values (LiveInRsp, LiveInRax),
2215   // this PHI should not be eliminated.
2216   JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI);
2217   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2218   // Expect no change.
2219   EXPECT_FALSE(Result);
2220   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2221   // This should not have been assigned a fixed value.
2222   EXPECT_EQ(JoinedLoc.ID, ValueIDNum::EmptyValue);
2223   EXPECT_EQ(JoinedLoc.BlockNo, 3);
2224 
2225   // Try a simple PHI elimination. Put a PHI in block 3, but LiveInRsp on both
2226   // incoming edges. Re-load in and out-locs with unrelated values; they're
2227   // irrelevant.
2228   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2229   VLiveOuts[2] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2230   JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI);
2231   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2232   EXPECT_TRUE(Result);
2233   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2234   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2235 
2236   // If the "current" live-in is a VPHI, but not a VPHI generated in the current
2237   // block, then it's the remains of an earlier value propagation. We should
2238   // value propagate through this merge. Even if the current incoming values
2239   // disagree, because we've previously determined any VPHI here is redundant.
2240   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2241   VLiveOuts[2] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2242   JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI);
2243   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2244   EXPECT_TRUE(Result);
2245   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2246   EXPECT_EQ(JoinedLoc.ID, LiveInRax); // from block 2
2247 
2248   // The above test, but test that we will install one value-propagated VPHI
2249   // over another.
2250   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2251   VLiveOuts[2] = DbgValue(0, EmptyProps, DbgValue::VPHI);
2252   JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI);
2253   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2254   EXPECT_TRUE(Result);
2255   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2256   EXPECT_EQ(JoinedLoc.BlockNo, 0);
2257 
2258   // We shouldn't eliminate PHIs when properties disagree.
2259   DbgValueProperties PropsWithIndirect(EmptyExpr, true);
2260   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2261   VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def);
2262   JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI);
2263   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2264   EXPECT_FALSE(Result);
2265   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2266   EXPECT_EQ(JoinedLoc.BlockNo, 3);
2267 
2268   // Even if properties disagree, we should still value-propagate if there's no
2269   // PHI to be eliminated. The disagreeing values should work themselves out,
2270   // seeing how we've determined no PHI is necessary.
2271   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2272   VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithIndirect, DbgValue::Def);
2273   JoinedLoc = DbgValue(2, EmptyProps, DbgValue::VPHI);
2274   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2275   EXPECT_TRUE(Result);
2276   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2277   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2278   // Also check properties come from block 2, the first RPO predecessor to block
2279   // three.
2280   EXPECT_EQ(JoinedLoc.Properties, PropsWithIndirect);
2281 
2282   // Again, disagreeing properties, this time the expr, should cause a PHI to
2283   // not be eliminated.
2284   DIExpression *NewExpr =
2285       DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4);
2286   DbgValueProperties PropsWithExpr(NewExpr, false);
2287   VLiveOuts[1] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2288   VLiveOuts[2] = DbgValue(LiveInRsp, PropsWithExpr, DbgValue::Def);
2289   JoinedLoc = DbgValue(3, EmptyProps, DbgValue::VPHI);
2290   Result = vlocJoin(*MBB3, VLiveOutIdx, AllBlocks, JoinedLoc);
2291   EXPECT_FALSE(Result);
2292 }
2293 
2294 TEST_F(InstrRefLDVTest, vlocJoinLoops) {
2295   setupSimpleLoop();
2296   //    entry
2297   //     |
2298   //     |/-----\
2299   //    loopblk |
2300   //     |\-----/
2301   //     |
2302   //     ret
2303   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2304   LocIdx RspLoc(0);
2305   Register RAX = getRegByName("RAX");
2306   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2307 
2308   unsigned EntryBlk = 0, LoopBlk = 1;
2309 
2310   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
2311   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
2312   ValueIDNum RspPHIInBlk1(LoopBlk, 0, RspLoc);
2313 
2314   DebugVariable Var(FuncVariable, None, nullptr);
2315   DbgValueProperties EmptyProps(EmptyExpr, false);
2316   SmallVector<DbgValue, 32> VLiveOuts;
2317   VLiveOuts.resize(3, DbgValue(EmptyProps, DbgValue::Undef));
2318   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
2319   VLiveOutIdx[MBB0] = &VLiveOuts[0];
2320   VLiveOutIdx[MBB1] = &VLiveOuts[1];
2321   VLiveOutIdx[MBB2] = &VLiveOuts[2];
2322 
2323   SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks;
2324   AllBlocks.insert(MBB0);
2325   AllBlocks.insert(MBB1);
2326   AllBlocks.insert(MBB2);
2327 
2328   SmallVector<const MachineBasicBlock *, 2> Preds;
2329   for (const auto *Pred : MBB1->predecessors())
2330     Preds.push_back(Pred);
2331 
2332   SmallSet<DebugVariable, 4> AllVars;
2333   AllVars.insert(Var);
2334 
2335   // Test some back-edge-specific behaviours of vloc join. Mostly: the fact that
2336   // VPHIs that arrive on backedges can be eliminated, despite having different
2337   // values to the predecessor.
2338 
2339   // First: when there's no VPHI placed already, propagate the live-in value of
2340   // the first RPO predecessor.
2341   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2342   VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2343   DbgValue JoinedLoc = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2344   bool Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2345   EXPECT_TRUE(Result);
2346   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2347   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2348 
2349   // If there is a VPHI: don't elimiante it if there are disagreeing values.
2350   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2351   VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2352   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2353   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2354   EXPECT_FALSE(Result);
2355   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2356   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2357 
2358   // If we feed this VPHI back into itself though, we can eliminate it.
2359   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2360   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2361   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2362   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2363   EXPECT_TRUE(Result);
2364   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2365   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2366 
2367   // Don't eliminate backedge VPHIs if the predecessors have different
2368   // properties.
2369   DIExpression *NewExpr =
2370       DIExpression::prepend(EmptyExpr, DIExpression::ApplyOffset, 4);
2371   DbgValueProperties PropsWithExpr(NewExpr, false);
2372   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2373   VLiveOuts[1] = DbgValue(1, PropsWithExpr, DbgValue::VPHI);
2374   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2375   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2376   EXPECT_FALSE(Result);
2377   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2378   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2379 
2380   // Backedges with VPHIs, but from the wrong block, shouldn't be eliminated.
2381   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2382   VLiveOuts[1] = DbgValue(0, EmptyProps, DbgValue::VPHI);
2383   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2384   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2385   EXPECT_FALSE(Result);
2386   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2387   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2388 }
2389 
2390 TEST_F(InstrRefLDVTest, vlocJoinBadlyNestedLoops) {
2391   // Test PHI elimination in the presence of multiple backedges.
2392   setupBadlyNestedLoops();
2393   //           entry
2394   //             |
2395   //           loop1 -o
2396   //             | ^
2397   //             | ^
2398   //           loop2 -o
2399   //             | ^
2400   //             | ^
2401   //           loop3 -o
2402   //             |
2403   //            ret
2404   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2405   LocIdx RspLoc(0);
2406   Register RAX = getRegByName("RAX");
2407   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2408   Register RBX = getRegByName("RBX");
2409   LocIdx RbxLoc = MTracker->lookupOrTrackRegister(RBX);
2410 
2411   unsigned EntryBlk = 0;
2412 
2413   ValueIDNum LiveInRsp(EntryBlk, 0, RspLoc);
2414   ValueIDNum LiveInRax(EntryBlk, 0, RaxLoc);
2415   ValueIDNum LiveInRbx(EntryBlk, 0, RbxLoc);
2416 
2417   DebugVariable Var(FuncVariable, None, nullptr);
2418   DbgValueProperties EmptyProps(EmptyExpr, false);
2419   SmallVector<DbgValue, 32> VLiveOuts;
2420   VLiveOuts.resize(5, DbgValue(EmptyProps, DbgValue::Undef));
2421   InstrRefBasedLDV::LiveIdxT VLiveOutIdx;
2422   VLiveOutIdx[MBB0] = &VLiveOuts[0];
2423   VLiveOutIdx[MBB1] = &VLiveOuts[1];
2424   VLiveOutIdx[MBB2] = &VLiveOuts[2];
2425   VLiveOutIdx[MBB3] = &VLiveOuts[3];
2426   VLiveOutIdx[MBB4] = &VLiveOuts[4];
2427 
2428   SmallPtrSet<const MachineBasicBlock *, 8> AllBlocks;
2429   AllBlocks.insert(MBB0);
2430   AllBlocks.insert(MBB1);
2431   AllBlocks.insert(MBB2);
2432   AllBlocks.insert(MBB3);
2433   AllBlocks.insert(MBB4);
2434 
2435   // We're going to focus on block 1.
2436   SmallVector<const MachineBasicBlock *, 3> Preds;
2437   for (const auto *Pred : MBB1->predecessors())
2438     Preds.push_back(Pred);
2439 
2440   SmallSet<DebugVariable, 4> AllVars;
2441   AllVars.insert(Var);
2442 
2443   // Test a normal VPHI isn't eliminated.
2444   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2445   VLiveOuts[1] = DbgValue(LiveInRax, EmptyProps, DbgValue::Def);
2446   VLiveOuts[2] = DbgValue(LiveInRbx, EmptyProps, DbgValue::Def);
2447   DbgValue JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2448   bool Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2449   EXPECT_FALSE(Result);
2450   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2451   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2452 
2453   // Common VPHIs on backedges should merge.
2454   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2455   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2456   VLiveOuts[2] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2457   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2458   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2459   EXPECT_TRUE(Result);
2460   EXPECT_EQ(JoinedLoc.Kind, DbgValue::Def);
2461   EXPECT_EQ(JoinedLoc.ID, LiveInRsp);
2462 
2463   // They shouldn't merge if one of their properties is different.
2464   DbgValueProperties PropsWithIndirect(EmptyExpr, true);
2465   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2466   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2467   VLiveOuts[2] = DbgValue(1, PropsWithIndirect, DbgValue::VPHI);
2468   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2469   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2470   EXPECT_FALSE(Result);
2471   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2472   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2473 
2474   // VPHIs from different blocks should not merge.
2475   VLiveOuts[0] = DbgValue(LiveInRsp, EmptyProps, DbgValue::Def);
2476   VLiveOuts[1] = DbgValue(1, EmptyProps, DbgValue::VPHI);
2477   VLiveOuts[2] = DbgValue(2, EmptyProps, DbgValue::VPHI);
2478   JoinedLoc = DbgValue(1, EmptyProps, DbgValue::VPHI);
2479   Result = vlocJoin(*MBB1, VLiveOutIdx, AllBlocks, JoinedLoc);
2480   EXPECT_FALSE(Result);
2481   EXPECT_EQ(JoinedLoc.Kind, DbgValue::VPHI);
2482   EXPECT_EQ(JoinedLoc.BlockNo, 1);
2483 }
2484 
2485 // Above are tests for picking VPHI locations, and eliminating VPHIs. No
2486 // unit-tests are written for evaluating the transfer function as that's
2487 // pretty straight forwards, or applying VPHI-location-picking to live-ins.
2488 // Instead, pre-set some machine locations and apply buildVLocValueMap to the
2489 // existing CFG patterns.
2490 TEST_F(InstrRefLDVTest, VLocSingleBlock) {
2491   setupSingleBlock();
2492 
2493   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2494   LocIdx RspLoc(0);
2495 
2496   ValueIDNum InLocs[2], OutLocs[2];
2497   ValueIDNum *InLocsPtr[1] = {&InLocs[0]};
2498   ValueIDNum *OutLocsPtr[1] = {&OutLocs[0]};
2499 
2500   ValueIDNum LiveInRsp = ValueIDNum(0, 0, RspLoc);
2501   InLocs[0] = OutLocs[0] = LiveInRsp;
2502 
2503   DebugVariable Var(FuncVariable, None, nullptr);
2504   DbgValueProperties EmptyProps(EmptyExpr, false);
2505 
2506   SmallSet<DebugVariable, 4> AllVars;
2507   AllVars.insert(Var);
2508 
2509   // Mild hack: rather than constructing machine instructions in each block
2510   // and creating lexical scopes across them, instead just tell
2511   // buildVLocValueMap that there's an assignment in every block. That makes
2512   // every block in scope.
2513   SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks;
2514   AssignBlocks.insert(MBB0);
2515 
2516   SmallVector<VLocTracker, 1> VLocs;
2517   VLocs.resize(1, VLocTracker(Overlaps, EmptyExpr));
2518 
2519   InstrRefBasedLDV::LiveInsT Output;
2520 
2521   // Test that, with no assignments at all, no mappings are created for the
2522   // variable in this function.
2523   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2524                     OutLocsPtr, InLocsPtr, VLocs);
2525   EXPECT_EQ(Output.size(), 0ul);
2526 
2527   // If we put an assignment in the transfer function, that should... well,
2528   // do nothing, because we don't store the live-outs.
2529   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2530   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2531                     OutLocsPtr, InLocsPtr, VLocs);
2532   EXPECT_EQ(Output.size(), 0ul);
2533 
2534   // There is pretty much nothing else of interest to test with a single block.
2535   // It's not relevant to the SSA-construction parts of variable values.
2536 }
2537 
2538 TEST_F(InstrRefLDVTest, VLocDiamondBlocks) {
2539   setupDiamondBlocks();
2540   //        entry
2541   //        /  \
2542   //      br1  br2
2543   //        \  /
2544   //         ret
2545 
2546   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2547   LocIdx RspLoc(0);
2548   Register RAX = getRegByName("RAX");
2549   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2550 
2551   unsigned EntryBlk = 0, RetBlk = 3;
2552 
2553   ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc);
2554   ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc);
2555   ValueIDNum RspPHIInBlk3 = ValueIDNum(RetBlk, 0, RspLoc);
2556 
2557   ValueIDNum InLocs[4][2], OutLocs[4][2];
2558   ValueIDNum *InLocsPtr[4] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3]};
2559   ValueIDNum *OutLocsPtr[4] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3]};
2560 
2561   initValueArray(InLocsPtr, 4, 2);
2562   initValueArray(OutLocsPtr, 4, 2);
2563 
2564   DebugVariable Var(FuncVariable, None, nullptr);
2565   DbgValueProperties EmptyProps(EmptyExpr, false);
2566 
2567   SmallSet<DebugVariable, 4> AllVars;
2568   AllVars.insert(Var);
2569 
2570   // Mild hack: rather than constructing machine instructions in each block
2571   // and creating lexical scopes across them, instead just tell
2572   // buildVLocValueMap that there's an assignment in every block. That makes
2573   // every block in scope.
2574   SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks;
2575   AssignBlocks.insert(MBB0);
2576   AssignBlocks.insert(MBB1);
2577   AssignBlocks.insert(MBB2);
2578   AssignBlocks.insert(MBB3);
2579 
2580   SmallVector<VLocTracker, 1> VLocs;
2581   VLocs.resize(4, VLocTracker(Overlaps, EmptyExpr));
2582 
2583   InstrRefBasedLDV::LiveInsT Output;
2584 
2585   // Start off with LiveInRsp in every location.
2586   for (unsigned int I = 0; I < 4; ++I) {
2587     InLocs[I][0] = InLocs[I][1] = LiveInRsp;
2588     OutLocs[I][0] = OutLocs[I][1] = LiveInRsp;
2589   }
2590 
2591   auto ClearOutputs = [&]() {
2592     for (auto &Elem : Output)
2593       Elem.clear();
2594   };
2595   Output.resize(4);
2596 
2597   // No assignments -> no values.
2598   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2599                     OutLocsPtr, InLocsPtr, VLocs);
2600   EXPECT_EQ(Output[0].size(), 0ul);
2601   EXPECT_EQ(Output[1].size(), 0ul);
2602   EXPECT_EQ(Output[2].size(), 0ul);
2603   EXPECT_EQ(Output[3].size(), 0ul);
2604 
2605   // An assignment in the end block should also not affect other blocks; or
2606   // produce any live-ins.
2607   VLocs[3].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2608   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2609                     OutLocsPtr, InLocsPtr, VLocs);
2610   EXPECT_EQ(Output[0].size(), 0ul);
2611   EXPECT_EQ(Output[1].size(), 0ul);
2612   EXPECT_EQ(Output[2].size(), 0ul);
2613   EXPECT_EQ(Output[3].size(), 0ul);
2614   ClearOutputs();
2615 
2616   // Assignments in either of the side-of-diamond blocks should also not be
2617   // propagated anywhere.
2618   VLocs[3].Vars.clear();
2619   VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2620   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2621                     OutLocsPtr, InLocsPtr, VLocs);
2622   EXPECT_EQ(Output[0].size(), 0ul);
2623   EXPECT_EQ(Output[1].size(), 0ul);
2624   EXPECT_EQ(Output[2].size(), 0ul);
2625   EXPECT_EQ(Output[3].size(), 0ul);
2626   VLocs[2].Vars.clear();
2627   ClearOutputs();
2628 
2629   VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2630   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2631                     OutLocsPtr, InLocsPtr, VLocs);
2632   EXPECT_EQ(Output[0].size(), 0ul);
2633   EXPECT_EQ(Output[1].size(), 0ul);
2634   EXPECT_EQ(Output[2].size(), 0ul);
2635   EXPECT_EQ(Output[3].size(), 0ul);
2636   VLocs[1].Vars.clear();
2637   ClearOutputs();
2638 
2639   // However: putting an assignment in the first block should propagate variable
2640   // values through to all other blocks, as it dominates.
2641   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2642   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2643                     OutLocsPtr, InLocsPtr, VLocs);
2644   EXPECT_EQ(Output[0].size(), 0ul);
2645   ASSERT_EQ(Output[1].size(), 1ul);
2646   ASSERT_EQ(Output[2].size(), 1ul);
2647   ASSERT_EQ(Output[3].size(), 1ul);
2648   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2649   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2650   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2651   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2652   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
2653   EXPECT_EQ(Output[3][0].second.ID, LiveInRsp);
2654   ClearOutputs();
2655   VLocs[0].Vars.clear();
2656 
2657   // Additionally, even if that value isn't available in the register file, it
2658   // should still be propagated, as buildVLocValueMap shouldn't care about
2659   // what's in the registers (except for PHIs).
2660   // values through to all other blocks, as it dominates.
2661   VLocs[0].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
2662   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2663                     OutLocsPtr, InLocsPtr, VLocs);
2664   EXPECT_EQ(Output[0].size(), 0ul);
2665   ASSERT_EQ(Output[1].size(), 1ul);
2666   ASSERT_EQ(Output[2].size(), 1ul);
2667   ASSERT_EQ(Output[3].size(), 1ul);
2668   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2669   EXPECT_EQ(Output[1][0].second.ID, LiveInRax);
2670   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2671   EXPECT_EQ(Output[2][0].second.ID, LiveInRax);
2672   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
2673   EXPECT_EQ(Output[3][0].second.ID, LiveInRax);
2674   ClearOutputs();
2675   VLocs[0].Vars.clear();
2676 
2677   // We should get a live-in to the merging block, if there are two assigns of
2678   // the same value in either side of the diamond.
2679   VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2680   VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2681   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2682                     OutLocsPtr, InLocsPtr, VLocs);
2683   EXPECT_EQ(Output[0].size(), 0ul);
2684   EXPECT_EQ(Output[1].size(), 0ul);
2685   EXPECT_EQ(Output[2].size(), 0ul);
2686   ASSERT_EQ(Output[3].size(), 1ul);
2687   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
2688   EXPECT_EQ(Output[3][0].second.ID, LiveInRsp);
2689   ClearOutputs();
2690   VLocs[1].Vars.clear();
2691   VLocs[2].Vars.clear();
2692 
2693   // If we assign a value in the entry block, then 'undef' on a branch, we
2694   // shouldn't have a live-in in the merge block.
2695   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2696   VLocs[1].Vars.insert({Var, DbgValue(EmptyProps, DbgValue::Undef)});
2697   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2698                     OutLocsPtr, InLocsPtr, VLocs);
2699   EXPECT_EQ(Output[0].size(), 0ul);
2700   ASSERT_EQ(Output[1].size(), 1ul);
2701   ASSERT_EQ(Output[2].size(), 1ul);
2702   EXPECT_EQ(Output[3].size(), 0ul);
2703   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2704   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2705   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2706   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2707   ClearOutputs();
2708   VLocs[0].Vars.clear();
2709   VLocs[1].Vars.clear();
2710 
2711   // Having different values joining into the merge block should mean we have
2712   // no live-in in that block. Block ones LiveInRax value doesn't appear as a
2713   // live-in anywhere, it's block internal.
2714   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2715   VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
2716   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2717                     OutLocsPtr, InLocsPtr, VLocs);
2718   EXPECT_EQ(Output[0].size(), 0ul);
2719   ASSERT_EQ(Output[1].size(), 1ul);
2720   ASSERT_EQ(Output[2].size(), 1ul);
2721   EXPECT_EQ(Output[3].size(), 0ul);
2722   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2723   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2724   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2725   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2726   ClearOutputs();
2727   VLocs[0].Vars.clear();
2728   VLocs[1].Vars.clear();
2729 
2730   // But on the other hand, if there's a location in the register file where
2731   // those two values can be joined, do so.
2732   OutLocs[1][0] = LiveInRax;
2733   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2734   VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
2735   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2736                     OutLocsPtr, InLocsPtr, VLocs);
2737   EXPECT_EQ(Output[0].size(), 0ul);
2738   ASSERT_EQ(Output[1].size(), 1ul);
2739   ASSERT_EQ(Output[2].size(), 1ul);
2740   ASSERT_EQ(Output[3].size(), 1ul);
2741   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2742   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2743   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2744   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2745   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
2746   EXPECT_EQ(Output[3][0].second.ID, RspPHIInBlk3);
2747   ClearOutputs();
2748   VLocs[0].Vars.clear();
2749   VLocs[1].Vars.clear();
2750 }
2751 
2752 TEST_F(InstrRefLDVTest, VLocSimpleLoop) {
2753   setupSimpleLoop();
2754   //    entry
2755   //     |
2756   //     |/-----\
2757   //    loopblk |
2758   //     |\-----/
2759   //     |
2760   //     ret
2761 
2762   ASSERT_TRUE(MTracker->getNumLocs() == 1);
2763   LocIdx RspLoc(0);
2764   Register RAX = getRegByName("RAX");
2765   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
2766 
2767   unsigned EntryBlk = 0, LoopBlk = 1;
2768 
2769   ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc);
2770   ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc);
2771   ValueIDNum RspPHIInBlk1 = ValueIDNum(LoopBlk, 0, RspLoc);
2772   ValueIDNum RspDefInBlk1 = ValueIDNum(LoopBlk, 1, RspLoc);
2773   ValueIDNum RaxPHIInBlk1 = ValueIDNum(LoopBlk, 0, RaxLoc);
2774 
2775   ValueIDNum InLocs[3][2], OutLocs[3][2];
2776   ValueIDNum *InLocsPtr[3] = {InLocs[0], InLocs[1], InLocs[2]};
2777   ValueIDNum *OutLocsPtr[3] = {OutLocs[0], OutLocs[1], OutLocs[2]};
2778 
2779   initValueArray(InLocsPtr, 3, 2);
2780   initValueArray(OutLocsPtr, 3, 2);
2781 
2782   DebugVariable Var(FuncVariable, None, nullptr);
2783   DbgValueProperties EmptyProps(EmptyExpr, false);
2784 
2785   SmallSet<DebugVariable, 4> AllVars;
2786   AllVars.insert(Var);
2787 
2788   SmallPtrSet<MachineBasicBlock *, 4> AssignBlocks;
2789   AssignBlocks.insert(MBB0);
2790   AssignBlocks.insert(MBB1);
2791   AssignBlocks.insert(MBB2);
2792 
2793   SmallVector<VLocTracker, 3> VLocs;
2794   VLocs.resize(3, VLocTracker(Overlaps, EmptyExpr));
2795 
2796   InstrRefBasedLDV::LiveInsT Output;
2797 
2798   // Start off with LiveInRsp in every location.
2799   for (unsigned int I = 0; I < 3; ++I) {
2800     InLocs[I][0] = InLocs[I][1] = LiveInRsp;
2801     OutLocs[I][0] = OutLocs[I][1] = LiveInRsp;
2802   }
2803 
2804   auto ClearOutputs = [&]() {
2805     for (auto &Elem : Output)
2806       Elem.clear();
2807   };
2808   Output.resize(3);
2809 
2810   // Easy starter: a dominating assign should propagate to all blocks.
2811   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2812   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2813                     OutLocsPtr, InLocsPtr, VLocs);
2814   EXPECT_EQ(Output[0].size(), 0ul);
2815   ASSERT_EQ(Output[1].size(), 1ul);
2816   ASSERT_EQ(Output[2].size(), 1ul);
2817   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2818   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2819   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2820   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2821   ClearOutputs();
2822   VLocs[0].Vars.clear();
2823   VLocs[1].Vars.clear();
2824 
2825   // Put an undef assignment in the loop. Should get no live-in value.
2826   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2827   VLocs[1].Vars.insert({Var, DbgValue(EmptyProps, DbgValue::Undef)});
2828   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2829                     OutLocsPtr, InLocsPtr, VLocs);
2830   EXPECT_EQ(Output[0].size(), 0ul);
2831   EXPECT_EQ(Output[1].size(), 0ul);
2832   EXPECT_EQ(Output[2].size(), 0ul);
2833   ClearOutputs();
2834   VLocs[0].Vars.clear();
2835   VLocs[1].Vars.clear();
2836 
2837   // Assignment of the same value should naturally join.
2838   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2839   VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2840   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2841                     OutLocsPtr, InLocsPtr, VLocs);
2842   EXPECT_EQ(Output[0].size(), 0ul);
2843   ASSERT_EQ(Output[1].size(), 1ul);
2844   ASSERT_EQ(Output[2].size(), 1ul);
2845   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2846   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2847   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2848   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2849   ClearOutputs();
2850   VLocs[0].Vars.clear();
2851   VLocs[1].Vars.clear();
2852 
2853   // Assignment of different values shouldn't join with no machine PHI vals.
2854   // Will be live-in to exit block as it's dominated.
2855   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2856   VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
2857   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2858                     OutLocsPtr, InLocsPtr, VLocs);
2859   EXPECT_EQ(Output[0].size(), 0ul);
2860   EXPECT_EQ(Output[1].size(), 0ul);
2861   ASSERT_EQ(Output[2].size(), 1ul);
2862   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2863   EXPECT_EQ(Output[2][0].second.ID, LiveInRax);
2864   ClearOutputs();
2865   VLocs[0].Vars.clear();
2866   VLocs[1].Vars.clear();
2867 
2868   // Install a completely unrelated PHI value, that we should not join on. Try
2869   // with unrelated assign in loop block again.
2870   InLocs[1][0] = RspPHIInBlk1;
2871   OutLocs[1][0] = RspDefInBlk1;
2872   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2873   VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
2874   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2875                     OutLocsPtr, InLocsPtr, VLocs);
2876   EXPECT_EQ(Output[0].size(), 0ul);
2877   EXPECT_EQ(Output[1].size(), 0ul);
2878   ASSERT_EQ(Output[2].size(), 1ul);
2879   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2880   EXPECT_EQ(Output[2][0].second.ID, LiveInRax);
2881   ClearOutputs();
2882   VLocs[0].Vars.clear();
2883   VLocs[1].Vars.clear();
2884 
2885   // Now, if we assign RspDefInBlk1 in the loop block, we should be able to
2886   // find the appropriate PHI.
2887   InLocs[1][0] = RspPHIInBlk1;
2888   OutLocs[1][0] = RspDefInBlk1;
2889   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2890   VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)});
2891   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2892                     OutLocsPtr, InLocsPtr, VLocs);
2893   EXPECT_EQ(Output[0].size(), 0ul);
2894   ASSERT_EQ(Output[1].size(), 1ul);
2895   ASSERT_EQ(Output[2].size(), 1ul);
2896   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2897   EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1);
2898   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2899   EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1);
2900   ClearOutputs();
2901   VLocs[0].Vars.clear();
2902   VLocs[1].Vars.clear();
2903 
2904   // If the PHI happens in a different location, the live-in should happen
2905   // there.
2906   InLocs[1][0] = LiveInRsp;
2907   OutLocs[1][0] = LiveInRsp;
2908   InLocs[1][1] = RaxPHIInBlk1;
2909   OutLocs[1][1] = RspDefInBlk1;
2910   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2911   VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)});
2912   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2913                     OutLocsPtr, InLocsPtr, VLocs);
2914   EXPECT_EQ(Output[0].size(), 0ul);
2915   ASSERT_EQ(Output[1].size(), 1ul);
2916   ASSERT_EQ(Output[2].size(), 1ul);
2917   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2918   EXPECT_EQ(Output[1][0].second.ID, RaxPHIInBlk1);
2919   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2920   EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1);
2921   ClearOutputs();
2922   VLocs[0].Vars.clear();
2923   VLocs[1].Vars.clear();
2924 
2925   // The PHI happening in both places should be handled too. Exactly where
2926   // isn't important, but if the location picked changes, this test will let
2927   // you know.
2928   InLocs[1][0] = RaxPHIInBlk1;
2929   OutLocs[1][0] = RspDefInBlk1;
2930   InLocs[1][1] = RaxPHIInBlk1;
2931   OutLocs[1][1] = RspDefInBlk1;
2932   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2933   VLocs[1].Vars.insert({Var, DbgValue(RspDefInBlk1, EmptyProps, DbgValue::Def)});
2934   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2935                     OutLocsPtr, InLocsPtr, VLocs);
2936   EXPECT_EQ(Output[0].size(), 0ul);
2937   ASSERT_EQ(Output[1].size(), 1ul);
2938   ASSERT_EQ(Output[2].size(), 1ul);
2939   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2940   // Today, the first register is picked.
2941   EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1);
2942   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2943   EXPECT_EQ(Output[2][0].second.ID, RspDefInBlk1);
2944   ClearOutputs();
2945   VLocs[0].Vars.clear();
2946   VLocs[1].Vars.clear();
2947 
2948   // If the loop block looked a bit like this:
2949   //    %0 = PHI %1, %2
2950   //    [...]
2951   //    DBG_VALUE %0
2952   // Then with instr-ref it becomes:
2953   //    DBG_PHI %0
2954   //    [...]
2955   //    DBG_INSTR_REF
2956   // And we would be feeding a machine PHI-value back around the loop. However:
2957   // this does not mean we can eliminate the variable value PHI and use the
2958   // variable value from the entry block: they are distinct values that must be
2959   // joined at some location by the control flow.
2960   // [This test input would never occur naturally, the machine-PHI would be
2961   //  eliminated]
2962   InLocs[1][0] = RspPHIInBlk1;
2963   OutLocs[1][0] = RspPHIInBlk1;
2964   InLocs[1][1] = LiveInRax;
2965   OutLocs[1][1] = LiveInRax;
2966   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2967   VLocs[1].Vars.insert({Var, DbgValue(RspPHIInBlk1, EmptyProps, DbgValue::Def)});
2968   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2969                     OutLocsPtr, InLocsPtr, VLocs);
2970   EXPECT_EQ(Output[0].size(), 0ul);
2971   ASSERT_EQ(Output[1].size(), 1ul);
2972   ASSERT_EQ(Output[2].size(), 1ul);
2973   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2974   EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1);
2975   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2976   EXPECT_EQ(Output[2][0].second.ID, RspPHIInBlk1);
2977   ClearOutputs();
2978   VLocs[0].Vars.clear();
2979   VLocs[1].Vars.clear();
2980 
2981   // Test that we can eliminate PHIs. A PHI will be placed at the loop head
2982   // because there's a def in in.
2983   InLocs[1][0] = LiveInRsp;
2984   OutLocs[1][0] = LiveInRsp;
2985   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2986   VLocs[1].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
2987   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
2988                     OutLocsPtr, InLocsPtr, VLocs);
2989   EXPECT_EQ(Output[0].size(), 0ul);
2990   ASSERT_EQ(Output[1].size(), 1ul);
2991   ASSERT_EQ(Output[2].size(), 1ul);
2992   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
2993   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
2994   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
2995   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
2996   ClearOutputs();
2997   VLocs[0].Vars.clear();
2998   VLocs[1].Vars.clear();
2999 }
3000 
3001 // test phi elimination with the nested situation
3002 TEST_F(InstrRefLDVTest, VLocNestedLoop) {
3003   //    entry
3004   //     |
3005   //    loop1
3006   //     ^\
3007   //     | \    /-\
3008   //     |  loop2  |
3009   //     |  /   \-/
3010   //     ^ /
3011   //     join
3012   //     |
3013   //     ret
3014   setupNestedLoops();
3015 
3016   ASSERT_TRUE(MTracker->getNumLocs() == 1);
3017   LocIdx RspLoc(0);
3018   Register RAX = getRegByName("RAX");
3019   LocIdx RaxLoc = MTracker->lookupOrTrackRegister(RAX);
3020 
3021   unsigned EntryBlk = 0, Loop1Blk = 1, Loop2Blk = 2;
3022 
3023   ValueIDNum LiveInRsp = ValueIDNum(EntryBlk, 0, RspLoc);
3024   ValueIDNum LiveInRax = ValueIDNum(EntryBlk, 0, RaxLoc);
3025   ValueIDNum RspPHIInBlk1 = ValueIDNum(Loop1Blk, 0, RspLoc);
3026   ValueIDNum RspPHIInBlk2 = ValueIDNum(Loop2Blk, 0, RspLoc);
3027   ValueIDNum RspDefInBlk2 = ValueIDNum(Loop2Blk, 1, RspLoc);
3028 
3029   ValueIDNum InLocs[5][2], OutLocs[5][2];
3030   ValueIDNum *InLocsPtr[5] = {InLocs[0], InLocs[1], InLocs[2], InLocs[3], InLocs[4]};
3031   ValueIDNum *OutLocsPtr[5] = {OutLocs[0], OutLocs[1], OutLocs[2], OutLocs[3], OutLocs[4]};
3032 
3033   initValueArray(InLocsPtr, 5, 2);
3034   initValueArray(OutLocsPtr, 5, 2);
3035 
3036   DebugVariable Var(FuncVariable, None, nullptr);
3037   DbgValueProperties EmptyProps(EmptyExpr, false);
3038 
3039   SmallSet<DebugVariable, 4> AllVars;
3040   AllVars.insert(Var);
3041 
3042   SmallPtrSet<MachineBasicBlock *, 5> AssignBlocks;
3043   AssignBlocks.insert(MBB0);
3044   AssignBlocks.insert(MBB1);
3045   AssignBlocks.insert(MBB2);
3046   AssignBlocks.insert(MBB3);
3047   AssignBlocks.insert(MBB4);
3048 
3049   SmallVector<VLocTracker, 5> VLocs;
3050   VLocs.resize(5, VLocTracker(Overlaps, EmptyExpr));
3051 
3052   InstrRefBasedLDV::LiveInsT Output;
3053 
3054   // Start off with LiveInRsp in every location.
3055   for (unsigned int I = 0; I < 5; ++I) {
3056     InLocs[I][0] = InLocs[I][1] = LiveInRsp;
3057     OutLocs[I][0] = OutLocs[I][1] = LiveInRsp;
3058   }
3059 
3060   auto ClearOutputs = [&]() {
3061     for (auto &Elem : Output)
3062       Elem.clear();
3063   };
3064   Output.resize(5);
3065 
3066   // A dominating assign should propagate to all blocks.
3067   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3068   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3069                     OutLocsPtr, InLocsPtr, VLocs);
3070   EXPECT_EQ(Output[0].size(), 0ul);
3071   ASSERT_EQ(Output[1].size(), 1ul);
3072   ASSERT_EQ(Output[2].size(), 1ul);
3073   ASSERT_EQ(Output[3].size(), 1ul);
3074   ASSERT_EQ(Output[4].size(), 1ul);
3075   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
3076   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
3077   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
3078   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
3079   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3080   EXPECT_EQ(Output[3][0].second.ID, LiveInRsp);
3081   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3082   EXPECT_EQ(Output[4][0].second.ID, LiveInRsp);
3083   ClearOutputs();
3084   VLocs[0].Vars.clear();
3085 
3086   // Test that an assign in the inner loop causes unresolved PHIs at the heads
3087   // of both loops, and no output location. Dominated blocks do get values.
3088   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3089   VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
3090   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3091                     OutLocsPtr, InLocsPtr, VLocs);
3092   EXPECT_EQ(Output[0].size(), 0ul);
3093   EXPECT_EQ(Output[1].size(), 0ul);
3094   EXPECT_EQ(Output[2].size(), 0ul);
3095   ASSERT_EQ(Output[3].size(), 1ul);
3096   ASSERT_EQ(Output[4].size(), 1ul);
3097   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3098   EXPECT_EQ(Output[3][0].second.ID, LiveInRax);
3099   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3100   EXPECT_EQ(Output[4][0].second.ID, LiveInRax);
3101   ClearOutputs();
3102   VLocs[0].Vars.clear();
3103   VLocs[2].Vars.clear();
3104 
3105   // Same test, but with no assignment in block 0. We should still get values
3106   // in dominated blocks.
3107   VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
3108   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3109                     OutLocsPtr, InLocsPtr, VLocs);
3110   EXPECT_EQ(Output[0].size(), 0ul);
3111   EXPECT_EQ(Output[1].size(), 0ul);
3112   EXPECT_EQ(Output[2].size(), 0ul);
3113   ASSERT_EQ(Output[3].size(), 1ul);
3114   ASSERT_EQ(Output[4].size(), 1ul);
3115   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3116   EXPECT_EQ(Output[3][0].second.ID, LiveInRax);
3117   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3118   EXPECT_EQ(Output[4][0].second.ID, LiveInRax);
3119   ClearOutputs();
3120   VLocs[2].Vars.clear();
3121 
3122   // Similarly, assignments in the outer loop gives location to dominated
3123   // blocks, but no PHI locations are found at the outer loop head.
3124   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3125   VLocs[3].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
3126   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3127                     OutLocsPtr, InLocsPtr, VLocs);
3128   EXPECT_EQ(Output[0].size(), 0ul);
3129   EXPECT_EQ(Output[1].size(), 0ul);
3130   EXPECT_EQ(Output[2].size(), 0ul);
3131   EXPECT_EQ(Output[3].size(), 0ul);
3132   ASSERT_EQ(Output[4].size(), 1ul);
3133   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3134   EXPECT_EQ(Output[4][0].second.ID, LiveInRax);
3135   ClearOutputs();
3136   VLocs[0].Vars.clear();
3137   VLocs[3].Vars.clear();
3138 
3139   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3140   VLocs[1].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
3141   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3142                     OutLocsPtr, InLocsPtr, VLocs);
3143   EXPECT_EQ(Output[0].size(), 0ul);
3144   EXPECT_EQ(Output[1].size(), 0ul);
3145   ASSERT_EQ(Output[2].size(), 1ul);
3146   ASSERT_EQ(Output[3].size(), 1ul);
3147   ASSERT_EQ(Output[4].size(), 1ul);
3148   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
3149   EXPECT_EQ(Output[2][0].second.ID, LiveInRax);
3150   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3151   EXPECT_EQ(Output[3][0].second.ID, LiveInRax);
3152   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3153   EXPECT_EQ(Output[4][0].second.ID, LiveInRax);
3154   ClearOutputs();
3155   VLocs[0].Vars.clear();
3156   VLocs[1].Vars.clear();
3157 
3158   // With an assignment of the same value in the inner loop, we should work out
3159   // that all PHIs can be eliminated and the same value is live-through the
3160   // whole function.
3161   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3162   VLocs[2].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3163   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3164                     OutLocsPtr, InLocsPtr, VLocs);
3165   EXPECT_EQ(Output[0].size(), 0ul);
3166   EXPECT_EQ(Output[1].size(), 1ul);
3167   EXPECT_EQ(Output[2].size(), 1ul);
3168   ASSERT_EQ(Output[3].size(), 1ul);
3169   ASSERT_EQ(Output[4].size(), 1ul);
3170   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
3171   EXPECT_EQ(Output[1][0].second.ID, LiveInRsp);
3172   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
3173   EXPECT_EQ(Output[2][0].second.ID, LiveInRsp);
3174   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3175   EXPECT_EQ(Output[3][0].second.ID, LiveInRsp);
3176   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3177   EXPECT_EQ(Output[4][0].second.ID, LiveInRsp);
3178   ClearOutputs();
3179   VLocs[0].Vars.clear();
3180   VLocs[2].Vars.clear();
3181 
3182   // If we have an assignment in the inner loop, and a PHI for it at the inner
3183   // loop head, we could find a live-in location for the inner loop. But because
3184   // the outer loop has no PHI, we can't find a variable value for outer loop
3185   // head, so can't have a live-in value for the inner loop head.
3186   InLocs[2][0] = RspPHIInBlk2;
3187   OutLocs[2][0] = LiveInRax;
3188   // NB: all other machine locations are LiveInRsp, disallowing a PHI in block
3189   // one. Even though RspPHIInBlk2 isn't available later in the function, we
3190   // should still produce a live-in value. The fact it's unavailable is a
3191   // different concern.
3192   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3193   VLocs[2].Vars.insert({Var, DbgValue(LiveInRax, EmptyProps, DbgValue::Def)});
3194   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3195                     OutLocsPtr, InLocsPtr, VLocs);
3196   EXPECT_EQ(Output[0].size(), 0ul);
3197   EXPECT_EQ(Output[1].size(), 0ul);
3198   EXPECT_EQ(Output[2].size(), 0ul);
3199   ASSERT_EQ(Output[3].size(), 1ul);
3200   ASSERT_EQ(Output[4].size(), 1ul);
3201   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3202   EXPECT_EQ(Output[3][0].second.ID, LiveInRax);
3203   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3204   EXPECT_EQ(Output[4][0].second.ID, LiveInRax);
3205   ClearOutputs();
3206   VLocs[0].Vars.clear();
3207   VLocs[2].Vars.clear();
3208 
3209   // Have an assignment in inner loop that can have a PHI resolved; and add a
3210   // machine value PHI to the outer loop head, so that we can find a location
3211   // all the way through the function.
3212   InLocs[1][0] = RspPHIInBlk1;
3213   OutLocs[1][0] = RspPHIInBlk1;
3214   InLocs[2][0] = RspPHIInBlk2;
3215   OutLocs[2][0] = RspDefInBlk2;
3216   InLocs[3][0] = RspDefInBlk2;
3217   OutLocs[3][0] = RspDefInBlk2;
3218   VLocs[0].Vars.insert({Var, DbgValue(LiveInRsp, EmptyProps, DbgValue::Def)});
3219   VLocs[2].Vars.insert({Var, DbgValue(RspDefInBlk2, EmptyProps, DbgValue::Def)});
3220   buildVLocValueMap(OutermostLoc, AllVars, AssignBlocks, Output,
3221                     OutLocsPtr, InLocsPtr, VLocs);
3222   EXPECT_EQ(Output[0].size(), 0ul);
3223   ASSERT_EQ(Output[1].size(), 1ul);
3224   ASSERT_EQ(Output[2].size(), 1ul);
3225   ASSERT_EQ(Output[3].size(), 1ul);
3226   ASSERT_EQ(Output[4].size(), 1ul);
3227   EXPECT_EQ(Output[1][0].second.Kind, DbgValue::Def);
3228   EXPECT_EQ(Output[1][0].second.ID, RspPHIInBlk1);
3229   EXPECT_EQ(Output[2][0].second.Kind, DbgValue::Def);
3230   EXPECT_EQ(Output[2][0].second.ID, RspPHIInBlk2);
3231   EXPECT_EQ(Output[3][0].second.Kind, DbgValue::Def);
3232   EXPECT_EQ(Output[3][0].second.ID, RspDefInBlk2);
3233   EXPECT_EQ(Output[4][0].second.Kind, DbgValue::Def);
3234   EXPECT_EQ(Output[4][0].second.ID, RspDefInBlk2);
3235   ClearOutputs();
3236   VLocs[0].Vars.clear();
3237   VLocs[2].Vars.clear();
3238 }
3239 
3240