blob: d8e95af9f4c7be2d1cc35c52fc848bd09be57de6 [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceCfgNode.cpp - Basic block (node) implementation -----===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
Jim Stichnoth92a6e5b2015-12-02 16:52:44 -080011/// \brief Implements the CfgNode class, including the complexities of
Andrew Scull57e12682015-09-16 11:30:19 -070012/// instruction insertion and in-edge calculation.
Andrew Scull9612d322015-07-06 14:53:25 -070013///
Jim Stichnothf7c9a142014-04-29 10:52:43 -070014//===----------------------------------------------------------------------===//
15
John Porto67f8de92015-06-25 10:14:17 -070016#include "IceCfgNode.h"
17
John Portoaff4ccf2015-06-10 16:35:06 -070018#include "IceAssembler.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070019#include "IceCfg.h"
John Portof8b4cc82015-06-09 18:06:19 -070020#include "IceGlobalInits.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070021#include "IceInst.h"
John Portoec3f5652015-08-31 15:07:09 -070022#include "IceInstVarIter.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070023#include "IceLiveness.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070024#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070025#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070026
27namespace Ice {
28
Andrew Scull57e12682015-09-16 11:30:19 -070029// Adds an instruction to either the Phi list or the regular instruction list.
30// Validates that all Phis are added before all regular instructions.
Eric Holk085bdae2016-04-18 15:08:19 -070031void CfgNode::appendInst(Inst *Instr) {
Jim Stichnoth47752552014-10-13 17:15:08 -070032 ++InstCountEstimate;
Eric Holk16f80612016-04-04 17:07:42 -070033
34 if (BuildDefs::wasm()) {
35 if (llvm::isa<InstSwitch>(Instr) || llvm::isa<InstBr>(Instr)) {
36 for (auto *N : Instr->getTerminatorEdges()) {
37 N->addInEdge(this);
38 addOutEdge(N);
39 }
40 }
41 }
42
Jim Stichnoth8cfeb692016-02-05 09:50:02 -080043 if (auto *Phi = llvm::dyn_cast<InstPhi>(Instr)) {
Eric Holk085bdae2016-04-18 15:08:19 -070044 if (!Insts.empty()) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -070045 Func->setError("Phi instruction added to the middle of a block");
46 return;
47 }
48 Phis.push_back(Phi);
49 } else {
Jim Stichnoth8cfeb692016-02-05 09:50:02 -080050 Insts.push_back(Instr);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070051 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -070052}
53
Manasij Mukherjee45f51a22016-06-27 16:12:37 -070054void CfgNode::replaceInEdge(CfgNode *Old, CfgNode *New) {
55 for (SizeT i = 0; i < InEdges.size(); ++i) {
56 if (InEdges[i] == Old) {
57 InEdges[i] = New;
58 }
59 }
60 for (auto &Inst : getPhis()) {
61 auto &Phi = llvm::cast<InstPhi>(Inst);
62 for (SizeT i = 0; i < Phi.getSrcSize(); ++i) {
63 if (Phi.getLabel(i) == Old) {
64 Phi.setLabel(i, New);
65 }
66 }
67 }
68}
69
Jim Stichnoth76719b42016-03-14 08:37:52 -070070namespace {
71template <typename List> void removeDeletedAndRenumber(List *L, Cfg *Func) {
72 const bool DoDelete =
Karl Schimpfd4699942016-04-02 09:55:31 -070073 BuildDefs::minimal() || !getFlags().getKeepDeletedInsts();
Jim Stichnoth76719b42016-03-14 08:37:52 -070074 auto I = L->begin(), E = L->end(), Next = I;
75 for (++Next; I != E; I = Next++) {
76 if (DoDelete && I->isDeleted()) {
Nicolas Capens038a9b92016-09-12 15:40:25 -040077 L->remove(I);
Jim Stichnoth76719b42016-03-14 08:37:52 -070078 } else {
79 I->renumber(Func);
80 }
81 }
82}
83} // end of anonymous namespace
84
Jim Stichnothd97c7df2014-06-04 11:57:08 -070085void CfgNode::renumberInstructions() {
Jim Stichnoth47752552014-10-13 17:15:08 -070086 InstNumberT FirstNumber = Func->getNextInstNumber();
Jim Stichnoth76719b42016-03-14 08:37:52 -070087 removeDeletedAndRenumber(&Phis, Func);
88 removeDeletedAndRenumber(&Insts, Func);
Jim Stichnoth47752552014-10-13 17:15:08 -070089 InstCountEstimate = Func->getNextInstNumber() - FirstNumber;
Jim Stichnothd97c7df2014-06-04 11:57:08 -070090}
91
Andrew Scull57e12682015-09-16 11:30:19 -070092// When a node is created, the OutEdges are immediately known, but the InEdges
93// have to be built up incrementally. After the CFG has been constructed, the
94// computePredecessors() pass finalizes it by creating the InEdges list.
Jim Stichnothf7c9a142014-04-29 10:52:43 -070095void CfgNode::computePredecessors() {
Jim Stichnothf44f3712014-10-01 14:05:51 -070096 for (CfgNode *Succ : OutEdges)
97 Succ->InEdges.push_back(this);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070098}
99
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700100void CfgNode::computeSuccessors() {
Eric Holk16f80612016-04-04 17:07:42 -0700101 OutEdges.clear();
102 InEdges.clear();
Eric Holk085bdae2016-04-18 15:08:19 -0700103 assert(!Insts.empty());
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700104 OutEdges = Insts.rbegin()->getTerminatorEdges();
105}
106
David Sehr263ac522016-04-04 10:11:08 -0700107// Ensure each Phi instruction in the node is consistent with respect to control
108// flow. For each predecessor, there must be a phi argument with that label.
109// If a phi argument's label doesn't appear in the predecessor list (which can
110// happen as a result of e.g. unreachable node elimination), its value is
111// modified to be zero, to maintain consistency in liveness analysis. This
112// allows us to remove some dead control flow without a major rework of the phi
113// instructions. We don't check that phi arguments with the same label have the
114// same value.
115void CfgNode::enforcePhiConsistency() {
Jim Stichnoth1aca2302015-09-16 11:25:22 -0700116 for (Inst &Instr : Phis) {
117 auto *Phi = llvm::cast<InstPhi>(&Instr);
Andrew Scull57e12682015-09-16 11:30:19 -0700118 // We do a simple O(N^2) algorithm to check for consistency. Even so, it
119 // shows up as only about 0.2% of the total translation time. But if
120 // necessary, we could improve the complexity by using a hash table to
121 // count how many times each node is referenced in the Phi instruction, and
122 // how many times each node is referenced in the incoming edge list, and
123 // compare the two for equality.
Jim Stichnoth1aca2302015-09-16 11:25:22 -0700124 for (SizeT i = 0; i < Phi->getSrcSize(); ++i) {
125 CfgNode *Label = Phi->getLabel(i);
126 bool Found = false;
127 for (CfgNode *InNode : getInEdges()) {
128 if (InNode == Label) {
129 Found = true;
130 break;
131 }
132 }
David Sehr263ac522016-04-04 10:11:08 -0700133 if (!Found) {
134 // Predecessor was unreachable, so if (impossibly) the control flow
135 // enters from that predecessor, the value should be zero.
136 Phi->clearOperandForTarget(Label);
137 }
Jim Stichnoth1aca2302015-09-16 11:25:22 -0700138 }
139 for (CfgNode *InNode : getInEdges()) {
140 bool Found = false;
141 for (SizeT i = 0; i < Phi->getSrcSize(); ++i) {
142 CfgNode *Label = Phi->getLabel(i);
143 if (InNode == Label) {
144 Found = true;
145 break;
146 }
147 }
148 if (!Found)
149 llvm::report_fatal_error("Phi error: missing label for incoming edge");
150 }
151 }
152}
153
Andrew Scull57e12682015-09-16 11:30:19 -0700154// This does part 1 of Phi lowering, by creating a new dest variable for each
155// Phi instruction, replacing the Phi instruction's dest with that variable,
156// and adding an explicit assignment of the old dest to the new dest. For
157// example,
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700158// a=phi(...)
159// changes to
160// "a_phi=phi(...); a=a_phi".
161//
Andrew Scull57e12682015-09-16 11:30:19 -0700162// This is in preparation for part 2 which deletes the Phi instructions and
163// appends assignment instructions to predecessor blocks. Note that this
164// transformation preserves SSA form.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700165void CfgNode::placePhiLoads() {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800166 for (Inst &I : Phis) {
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700167 auto *Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800168 Insts.insert(Insts.begin(), Phi->lower(Func));
169 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700170}
171
Andrew Scull57e12682015-09-16 11:30:19 -0700172// This does part 2 of Phi lowering. For each Phi instruction at each out-edge,
173// create a corresponding assignment instruction, and add all the assignments
174// near the end of this block. They need to be added before any branch
175// instruction, and also if the block ends with a compare instruction followed
176// by a branch instruction that we may want to fuse, it's better to insert the
177// new assignments before the compare instruction. The
178// tryOptimizedCmpxchgCmpBr() method assumes this ordering of instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700179//
Andrew Scull57e12682015-09-16 11:30:19 -0700180// Note that this transformation takes the Phi dest variables out of SSA form,
181// as there may be assignments to the dest variable in multiple blocks.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700182void CfgNode::placePhiStores() {
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700183 // Find the insertion point.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700184 InstList::iterator InsertionPoint = Insts.end();
Andrew Scull57e12682015-09-16 11:30:19 -0700185 // Every block must end in a terminator instruction, and therefore must have
186 // at least one instruction, so it's valid to decrement InsertionPoint (but
187 // assert just in case).
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700188 assert(InsertionPoint != Insts.begin());
189 --InsertionPoint;
Andrew Scull57e12682015-09-16 11:30:19 -0700190 // Confirm that InsertionPoint is a terminator instruction. Calling
191 // getTerminatorEdges() on a non-terminator instruction will cause an
192 // llvm_unreachable().
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800193 (void)InsertionPoint->getTerminatorEdges();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700194 // SafeInsertionPoint is always immediately before the terminator
Andrew Scull57e12682015-09-16 11:30:19 -0700195 // instruction. If the block ends in a compare and conditional branch, it's
196 // better to place the Phi store before the compare so as not to interfere
197 // with compare/branch fusing. However, if the compare instruction's dest
198 // operand is the same as the new assignment statement's source operand, this
199 // can't be done due to data dependences, so we need to fall back to the
200 // SafeInsertionPoint. To illustrate:
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700201 // ; <label>:95
202 // %97 = load i8* %96, align 1
203 // %98 = icmp ne i8 %97, 0
204 // br i1 %98, label %99, label %2132
205 // ; <label>:99
206 // %100 = phi i8 [ %97, %95 ], [ %110, %108 ]
207 // %101 = phi i1 [ %98, %95 ], [ %111, %108 ]
208 // would be Phi-lowered as:
209 // ; <label>:95
210 // %97 = load i8* %96, align 1
211 // %100_phi = %97 ; can be at InsertionPoint
212 // %98 = icmp ne i8 %97, 0
213 // %101_phi = %98 ; must be at SafeInsertionPoint
214 // br i1 %98, label %99, label %2132
215 // ; <label>:99
216 // %100 = %100_phi
217 // %101 = %101_phi
218 //
Andrew Scull57e12682015-09-16 11:30:19 -0700219 // TODO(stichnot): It may be possible to bypass this whole SafeInsertionPoint
220 // mechanism. If a source basic block ends in a conditional branch:
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700221 // labelSource:
222 // ...
223 // br i1 %foo, label %labelTrue, label %labelFalse
224 // and a branch target has a Phi involving the branch operand:
225 // labelTrue:
226 // %bar = phi i1 [ %foo, %labelSource ], ...
227 // then we actually know the constant i1 value of the Phi operand:
228 // labelTrue:
229 // %bar = phi i1 [ true, %labelSource ], ...
Andrew Scull57e12682015-09-16 11:30:19 -0700230 // It seems that this optimization should be done by clang or opt, but we
231 // could also do it here.
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700232 InstList::iterator SafeInsertionPoint = InsertionPoint;
Andrew Scull57e12682015-09-16 11:30:19 -0700233 // Keep track of the dest variable of a compare instruction, so that we
234 // insert the new instruction at the SafeInsertionPoint if the compare's dest
235 // matches the Phi-lowered assignment's source.
Jim Stichnothae953202014-12-20 06:17:49 -0800236 Variable *CmpInstDest = nullptr;
Andrew Scull57e12682015-09-16 11:30:19 -0700237 // If the current insertion point is at a conditional branch instruction, and
238 // the previous instruction is a compare instruction, then we move the
239 // insertion point before the compare instruction so as not to interfere with
240 // compare/branch fusing.
Jim Stichnoth54f3d512015-12-11 09:53:00 -0800241 if (auto *Branch = llvm::dyn_cast<InstBr>(InsertionPoint)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700242 if (!Branch->isUnconditional()) {
243 if (InsertionPoint != Insts.begin()) {
244 --InsertionPoint;
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800245 if (llvm::isa<InstIcmp>(InsertionPoint) ||
246 llvm::isa<InstFcmp>(InsertionPoint)) {
247 CmpInstDest = InsertionPoint->getDest();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700248 } else {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700249 ++InsertionPoint;
250 }
251 }
252 }
253 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700254
255 // Consider every out-edge.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700256 for (CfgNode *Succ : OutEdges) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700257 // Consider every Phi instruction at the out-edge.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800258 for (Inst &I : Succ->Phis) {
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700259 auto *Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800260 Operand *Operand = Phi->getOperandForTarget(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700261 assert(Operand);
Jim Stichnoth29841e82014-12-23 12:26:24 -0800262 Variable *Dest = I.getDest();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700263 assert(Dest);
Jim Stichnoth54f3d512015-12-11 09:53:00 -0800264 auto *NewInst = InstAssign::create(Func, Dest, Operand);
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700265 if (CmpInstDest == Operand)
266 Insts.insert(SafeInsertionPoint, NewInst);
267 else
268 Insts.insert(InsertionPoint, NewInst);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700269 }
270 }
271}
272
273// Deletes the phi instructions after the loads and stores are placed.
274void CfgNode::deletePhis() {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800275 for (Inst &I : Phis)
276 I.setDeleted();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700277}
278
Andrew Scull57e12682015-09-16 11:30:19 -0700279// Splits the edge from Pred to this node by creating a new node and hooking up
280// the in and out edges appropriately. (The EdgeIndex parameter is only used to
281// make the new node's name unique when there are multiple edges between the
282// same pair of nodes.) The new node's instruction list is initialized to the
283// empty list, with no terminator instruction. There must not be multiple edges
284// from Pred to this node so all Inst::getTerminatorEdges implementations must
Andrew Scull87f80c12015-07-20 10:19:16 -0700285// not contain duplicates.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700286CfgNode *CfgNode::splitIncomingEdge(CfgNode *Pred, SizeT EdgeIndex) {
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800287 CfgNode *NewNode = Func->makeNode();
Andrew Scullaa6c1092015-09-03 17:50:30 -0700288 // Depth is the minimum as it works if both are the same, but if one is
289 // outside the loop and the other is inside, the new node should be placed
290 // outside and not be executed multiple times within the loop.
291 NewNode->setLoopNestDepth(
292 std::min(getLoopNestDepth(), Pred->getLoopNestDepth()));
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700293 if (BuildDefs::dump())
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800294 NewNode->setName("split_" + Pred->getName() + "_" + getName() + "_" +
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700295 std::to_string(EdgeIndex));
Andrew Scull57e12682015-09-16 11:30:19 -0700296 // The new node is added to the end of the node list, and will later need to
297 // be sorted into a reasonable topological order.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700298 NewNode->setNeedsPlacement(true);
299 // Repoint Pred's out-edge.
300 bool Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700301 for (CfgNode *&I : Pred->OutEdges) {
302 if (I == this) {
303 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700304 NewNode->InEdges.push_back(Pred);
305 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700306 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700307 }
308 }
309 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700310 (void)Found;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700311 // Repoint this node's in-edge.
312 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700313 for (CfgNode *&I : InEdges) {
314 if (I == Pred) {
315 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700316 NewNode->OutEdges.push_back(this);
317 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700318 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700319 }
320 }
321 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700322 (void)Found;
Andrew Scull87f80c12015-07-20 10:19:16 -0700323 // Repoint all suitable branch instructions' target and return.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700324 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700325 for (Inst &I : Pred->getInsts())
326 if (!I.isDeleted() && I.repointEdges(this, NewNode))
327 Found = true;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700328 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700329 (void)Found;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700330 return NewNode;
331}
332
333namespace {
334
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800335// Helpers for advancedPhiLowering().
336
337class PhiDesc {
338 PhiDesc() = delete;
339 PhiDesc(const PhiDesc &) = delete;
340 PhiDesc &operator=(const PhiDesc &) = delete;
Jim Stichnothc59288b2015-11-09 11:38:40 -0800341
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800342public:
343 PhiDesc(InstPhi *Phi, Variable *Dest) : Phi(Phi), Dest(Dest) {}
344 PhiDesc(PhiDesc &&) = default;
345 InstPhi *Phi = nullptr;
346 Variable *Dest = nullptr;
347 Operand *Src = nullptr;
348 bool Processed = false;
349 size_t NumPred = 0; // number of entries whose Src is this Dest
350 int32_t Weight = 0; // preference for topological order
351};
352using PhiDescList = llvm::SmallVector<PhiDesc, 32>;
353
354// Always pick NumPred=0 over NumPred>0.
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700355constexpr int32_t WeightNoPreds = 8;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800356// Prefer Src as a register because the register might free up.
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700357constexpr int32_t WeightSrcIsReg = 4;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800358// Prefer Dest not as a register because the register stays free longer.
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700359constexpr int32_t WeightDestNotReg = 2;
360// Prefer NumPred=1 over NumPred>1. This is used as a tiebreaker when a
361// dependency cycle must be broken so that hopefully only one temporary
362// assignment has to be added to break the cycle.
363constexpr int32_t WeightOnePred = 1;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800364
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700365bool sameVarOrReg(TargetLowering *Target, const Variable *Var1,
366 const Operand *Opnd) {
367 if (Var1 == Opnd)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700368 return true;
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700369 const auto *Var2 = llvm::dyn_cast<Variable>(Opnd);
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700370 if (Var2 == nullptr)
371 return false;
372
373 // If either operand lacks a register, they cannot be the same.
374 if (!Var1->hasReg())
375 return false;
376 if (!Var2->hasReg())
377 return false;
378
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800379 const auto RegNum1 = Var1->getRegNum();
380 const auto RegNum2 = Var2->getRegNum();
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700381 // Quick common-case check.
382 if (RegNum1 == RegNum2)
383 return true;
384
385 assert(Target->getAliasesForRegister(RegNum1)[RegNum2] ==
386 Target->getAliasesForRegister(RegNum2)[RegNum1]);
387 return Target->getAliasesForRegister(RegNum1)[RegNum2];
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700388}
389
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800390// Update NumPred for all Phi assignments using Var as their Dest variable.
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700391// Also update Weight if NumPred dropped from 2 to 1, or 1 to 0.
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800392void updatePreds(PhiDescList &Desc, TargetLowering *Target, Variable *Var) {
393 for (PhiDesc &Item : Desc) {
394 if (!Item.Processed && sameVarOrReg(Target, Var, Item.Dest)) {
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700395 --Item.NumPred;
396 if (Item.NumPred == 1) {
397 // If NumPred changed from 2 to 1, add in WeightOnePred.
398 Item.Weight += WeightOnePred;
399 } else if (Item.NumPred == 0) {
400 // If NumPred changed from 1 to 0, subtract WeightOnePred and add in
401 // WeightNoPreds.
402 Item.Weight += (WeightNoPreds - WeightOnePred);
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800403 }
404 }
405 }
406}
407
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700408} // end of anonymous namespace
409
Andrew Scull57e12682015-09-16 11:30:19 -0700410// This the "advanced" version of Phi lowering for a basic block, in contrast
411// to the simple version that lowers through assignments involving temporaries.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700412//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700413// All Phi instructions in a basic block are conceptually executed in parallel.
414// However, if we lower Phis early and commit to a sequential ordering, we may
415// end up creating unnecessary interferences which lead to worse register
Andrew Scull57e12682015-09-16 11:30:19 -0700416// allocation. Delaying Phi scheduling until after register allocation can help
417// unless there are no free registers for shuffling registers or stack slots
418// and spilling becomes necessary.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700419//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700420// The advanced Phi lowering starts by finding a topological sort of the Phi
Andrew Scull57e12682015-09-16 11:30:19 -0700421// instructions, where "A=B" comes before "B=C" due to the anti-dependence on
422// B. Preexisting register assignments are considered in the topological sort.
423// If a topological sort is not possible due to a cycle, the cycle is broken by
424// introducing a non-parallel temporary. For example, a cycle arising from a
425// permutation like "A=B;B=C;C=A" can become "T=A;A=B;B=C;C=T". All else being
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700426// equal, prefer to schedule assignments with register-allocated Src operands
427// earlier, in case that register becomes free afterwards, and prefer to
428// schedule assignments with register-allocated Dest variables later, to keep
429// that register free for longer.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700430//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700431// Once the ordering is determined, the Cfg edge is split and the assignment
Andrew Scull57e12682015-09-16 11:30:19 -0700432// list is lowered by the target lowering layer. Since the assignment lowering
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700433// may create new infinite-weight temporaries, a follow-on register allocation
Andrew Scull57e12682015-09-16 11:30:19 -0700434// pass will be needed. To prepare for this, liveness (including live range
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700435// calculation) of the split nodes needs to be calculated, and liveness of the
436// original node need to be updated to "undo" the effects of the phi
437// assignments.
438
439// The specific placement of the new node within the Cfg node list is deferred
440// until later, including after empty node contraction.
441//
442// After phi assignments are lowered across all blocks, another register
443// allocation pass is run, focusing only on pre-colored and infinite-weight
444// variables, similar to Om1 register allocation (except without the need to
445// specially compute these variables' live ranges, since they have already been
Andrew Scull57e12682015-09-16 11:30:19 -0700446// precisely calculated). The register allocator in this mode needs the ability
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700447// to forcibly spill and reload registers in case none are naturally available.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700448void CfgNode::advancedPhiLowering() {
449 if (getPhis().empty())
450 return;
451
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800452 PhiDescList Desc;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700453
Jim Stichnoth29841e82014-12-23 12:26:24 -0800454 for (Inst &I : Phis) {
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800455 auto *Phi = llvm::dyn_cast<InstPhi>(&I);
456 if (!Phi->isDeleted()) {
457 Variable *Dest = Phi->getDest();
458 Desc.emplace_back(Phi, Dest);
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700459 // Undo the effect of the phi instruction on this node's live-in set by
460 // marking the phi dest variable as live on entry.
461 SizeT VarNum = Func->getLiveness()->getLiveIndex(Dest->getIndex());
Manasij Mukherjee7cd926d2016-08-04 12:33:23 -0700462 auto &LiveIn = Func->getLiveness()->getLiveIn(this);
463 if (VarNum < LiveIn.size()) {
464 assert(!LiveIn[VarNum]);
465 LiveIn[VarNum] = true;
466 }
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800467 Phi->setDeleted();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700468 }
469 }
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800470 if (Desc.empty())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700471 return;
472
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700473 TargetLowering *Target = Func->getTarget();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700474 SizeT InEdgeIndex = 0;
475 for (CfgNode *Pred : InEdges) {
476 CfgNode *Split = splitIncomingEdge(Pred, InEdgeIndex++);
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800477 SizeT Remaining = Desc.size();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700478
479 // First pass computes Src and initializes NumPred.
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800480 for (PhiDesc &Item : Desc) {
481 Variable *Dest = Item.Dest;
482 Operand *Src = Item.Phi->getOperandForTarget(Pred);
483 Item.Src = Src;
484 Item.Processed = false;
485 Item.NumPred = 0;
Andrew Scull57e12682015-09-16 11:30:19 -0700486 // Cherry-pick any trivial assignments, so that they don't contribute to
487 // the running complexity of the topological sort.
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700488 if (sameVarOrReg(Target, Dest, Src)) {
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800489 Item.Processed = true;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700490 --Remaining;
491 if (Dest != Src)
Andrew Scull57e12682015-09-16 11:30:19 -0700492 // If Dest and Src are syntactically the same, don't bother adding
493 // the assignment, because in all respects it would be redundant, and
494 // if Dest/Src are on the stack, the target lowering may naively
495 // decide to lower it using a temporary register.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700496 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700497 }
498 }
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800499 // Second pass computes NumPred by comparing every pair of Phi instructions.
500 for (PhiDesc &Item : Desc) {
501 if (Item.Processed)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700502 continue;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800503 const Variable *Dest = Item.Dest;
504 for (PhiDesc &Item2 : Desc) {
505 if (Item2.Processed)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700506 continue;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800507 // There shouldn't be two different Phis with the same Dest variable or
Jim Stichnothc59288b2015-11-09 11:38:40 -0800508 // register.
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800509 assert((&Item == &Item2) || !sameVarOrReg(Target, Dest, Item2.Dest));
510 if (sameVarOrReg(Target, Dest, Item2.Src))
511 ++Item.NumPred;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700512 }
513 }
514
515 // Another pass to compute initial Weight values.
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800516 for (PhiDesc &Item : Desc) {
517 if (Item.Processed)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700518 continue;
519 int32_t Weight = 0;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800520 if (Item.NumPred == 0)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700521 Weight += WeightNoPreds;
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700522 if (Item.NumPred == 1)
523 Weight += WeightOnePred;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800524 if (auto *Var = llvm::dyn_cast<Variable>(Item.Src))
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700525 if (Var->hasReg())
526 Weight += WeightSrcIsReg;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800527 if (!Item.Dest->hasReg())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700528 Weight += WeightDestNotReg;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800529 Item.Weight = Weight;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700530 }
531
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800532 // Repeatedly choose and process the best candidate in the topological sort,
533 // until no candidates remain. This implementation is O(N^2) where N is the
534 // number of Phi instructions, but with a small constant factor compared to
535 // a likely implementation of O(N) topological sort.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700536 for (; Remaining; --Remaining) {
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700537 int32_t BestWeight = -1;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800538 PhiDesc *BestItem = nullptr;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700539 // Find the best candidate.
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800540 for (PhiDesc &Item : Desc) {
541 if (Item.Processed)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700542 continue;
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700543 const int32_t Weight = Item.Weight;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700544 if (Weight > BestWeight) {
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800545 BestItem = &Item;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700546 BestWeight = Weight;
547 }
548 }
549 assert(BestWeight >= 0);
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800550 Variable *Dest = BestItem->Dest;
551 Operand *Src = BestItem->Src;
Jim Stichnoth1fb030c2015-10-15 11:10:38 -0700552 assert(!sameVarOrReg(Target, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700553 // Break a cycle by introducing a temporary.
Jim Stichnothbbd449d2016-03-30 15:30:30 -0700554 while (BestItem->NumPred > 0) {
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700555 bool Found = false;
Andrew Scull57e12682015-09-16 11:30:19 -0700556 // If the target instruction "A=B" is part of a cycle, find the "X=A"
557 // assignment in the cycle because it will have to be rewritten as
558 // "X=tmp".
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800559 for (PhiDesc &Item : Desc) {
560 if (Item.Processed)
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700561 continue;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800562 Operand *OtherSrc = Item.Src;
563 if (Item.NumPred && sameVarOrReg(Target, Dest, OtherSrc)) {
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700564 SizeT VarNum = Func->getNumVariables();
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800565 Variable *Tmp = Func->makeVariable(OtherSrc->getType());
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700566 if (BuildDefs::dump())
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800567 Tmp->setName(Func, "__split_" + std::to_string(VarNum));
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700568 Split->appendInst(InstAssign::create(Func, Tmp, OtherSrc));
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800569 Item.Src = Tmp;
570 updatePreds(Desc, Target, llvm::cast<Variable>(OtherSrc));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700571 Found = true;
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800572 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700573 }
574 }
575 assert(Found);
Jim Stichnothb0051df2016-01-13 11:39:15 -0800576 (void)Found;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700577 }
578 // Now that a cycle (if any) has been broken, create the actual
579 // assignment.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700580 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800581 if (auto *Var = llvm::dyn_cast<Variable>(Src))
582 updatePreds(Desc, Target, Var);
583 BestItem->Processed = true;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700584 }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700585 Split->appendInst(InstBr::create(Func, this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700586
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700587 Split->genCode();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700588 Func->getVMetadata()->addNode(Split);
Jim Stichnothea15bbe2015-11-09 11:19:11 -0800589 // Validate to be safe. All items should be marked as processed, and have
590 // no predecessors.
591 if (BuildDefs::asserts()) {
592 for (PhiDesc &Item : Desc) {
593 (void)Item;
594 assert(Item.Processed);
595 assert(Item.NumPred == 0);
596 }
597 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700598 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700599}
600
Andrew Scull57e12682015-09-16 11:30:19 -0700601// Does address mode optimization. Pass each instruction to the TargetLowering
602// object. If it returns a new instruction (representing the optimized address
603// mode), then insert the new instruction and delete the old.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700604void CfgNode::doAddressOpt() {
605 TargetLowering *Target = Func->getTarget();
606 LoweringContext &Context = Target->getContext();
607 Context.init(this);
608 while (!Context.atEnd()) {
609 Target->doAddressOpt();
610 }
611}
612
Qining Luaee5fa82015-08-20 14:59:03 -0700613void CfgNode::doNopInsertion(RandomNumberGenerator &RNG) {
Matt Walac3302742014-08-15 16:21:56 -0700614 TargetLowering *Target = Func->getTarget();
615 LoweringContext &Context = Target->getContext();
616 Context.init(this);
Qining Lu969f6a32015-07-31 09:58:34 -0700617 Context.setInsertPoint(Context.getCur());
618 // Do not insert nop in bundle locked instructions.
619 bool PauseNopInsertion = false;
Matt Walac3302742014-08-15 16:21:56 -0700620 while (!Context.atEnd()) {
Qining Lu969f6a32015-07-31 09:58:34 -0700621 if (llvm::isa<InstBundleLock>(Context.getCur())) {
622 PauseNopInsertion = true;
623 } else if (llvm::isa<InstBundleUnlock>(Context.getCur())) {
624 PauseNopInsertion = false;
625 }
626 if (!PauseNopInsertion)
Qining Luaee5fa82015-08-20 14:59:03 -0700627 Target->doNopInsertion(RNG);
Matt Walac3302742014-08-15 16:21:56 -0700628 // Ensure Cur=Next, so that the nops are inserted before the current
629 // instruction rather than after.
Matt Walac3302742014-08-15 16:21:56 -0700630 Context.advanceCur();
Qining Lu969f6a32015-07-31 09:58:34 -0700631 Context.advanceNext();
Matt Walac3302742014-08-15 16:21:56 -0700632 }
Matt Walac3302742014-08-15 16:21:56 -0700633}
634
Andrew Scull57e12682015-09-16 11:30:19 -0700635// Drives the target lowering. Passes the current instruction and the next
636// non-deleted instruction for target lowering.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700637void CfgNode::genCode() {
638 TargetLowering *Target = Func->getTarget();
639 LoweringContext &Context = Target->getContext();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700640 // Lower the regular instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700641 Context.init(this);
Jim Stichnotha59ae6f2015-05-17 10:11:41 -0700642 Target->initNodeForLowering(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700643 while (!Context.atEnd()) {
644 InstList::iterator Orig = Context.getCur();
645 if (llvm::isa<InstRet>(*Orig))
646 setHasReturn();
647 Target->lower();
648 // Ensure target lowering actually moved the cursor.
649 assert(Context.getCur() != Orig);
650 }
Jim Stichnoth318f4cd2015-10-01 21:02:37 -0700651 Context.availabilityReset();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700652 // Do preliminary lowering of the Phi instructions.
653 Target->prelowerPhis();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700654}
655
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700656void CfgNode::livenessLightweight() {
657 SizeT NumVars = Func->getNumVariables();
Jim Stichnoth47752552014-10-13 17:15:08 -0700658 LivenessBV Live(NumVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700659 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800660 for (Inst &I : reverse_range(Insts)) {
661 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700662 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800663 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700664 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800665 for (Inst &I : Phis) {
666 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700667 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800668 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700669 }
670}
671
Andrew Scull57e12682015-09-16 11:30:19 -0700672// Performs liveness analysis on the block. Returns true if the incoming
673// liveness changed from before, false if it stayed the same. (If it changes,
674// the node's predecessors need to be processed again.)
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700675bool CfgNode::liveness(Liveness *Liveness) {
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800676 const SizeT NumVars = Liveness->getNumVarsInNode(this);
677 const SizeT NumGlobalVars = Liveness->getNumGlobalVars();
678 LivenessBV &Live = Liveness->getScratchBV();
679 Live.clear();
680
Jim Stichnothae953202014-12-20 06:17:49 -0800681 LiveBeginEndMap *LiveBegin = nullptr;
682 LiveBeginEndMap *LiveEnd = nullptr;
Andrew Scull57e12682015-09-16 11:30:19 -0700683 // Mark the beginning and ending of each variable's live range with the
684 // sentinel instruction number 0.
Jim Stichnoth47752552014-10-13 17:15:08 -0700685 if (Liveness->getMode() == Liveness_Intervals) {
686 LiveBegin = Liveness->getLiveBegin(this);
687 LiveEnd = Liveness->getLiveEnd(this);
688 LiveBegin->clear();
689 LiveEnd->clear();
Andrew Scull57e12682015-09-16 11:30:19 -0700690 // Guess that the number of live ranges beginning is roughly the number of
691 // instructions, and same for live ranges ending.
Jim Stichnoth47752552014-10-13 17:15:08 -0700692 LiveBegin->reserve(getInstCountEstimate());
693 LiveEnd->reserve(getInstCountEstimate());
694 }
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800695
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700696 // Initialize Live to be the union of all successors' LiveIn.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700697 for (CfgNode *Succ : OutEdges) {
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800698 const LivenessBV &LiveIn = Liveness->getLiveIn(Succ);
699 assert(LiveIn.empty() || LiveIn.size() == NumGlobalVars);
700 Live |= LiveIn;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700701 // Mark corresponding argument of phis in successor as live.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800702 for (Inst &I : Succ->Phis) {
Jim Stichnoth552490c2015-08-05 16:21:42 -0700703 if (I.isDeleted())
704 continue;
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800705 auto *Phi = llvm::cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800706 Phi->livenessPhiOperand(Live, this, Liveness);
707 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700708 }
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800709 assert(Live.empty() || Live.size() == NumGlobalVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700710 Liveness->getLiveOut(this) = Live;
711
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800712 // Expand Live so it can hold locals in addition to globals.
713 Live.resize(NumVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700714 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800715 for (Inst &I : reverse_range(Insts)) {
716 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700717 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800718 I.liveness(I.getNumber(), Live, Liveness, LiveBegin, LiveEnd);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700719 }
Andrew Scull57e12682015-09-16 11:30:19 -0700720 // Process phis in forward order so that we can override the instruction
721 // number to be that of the earliest phi instruction in the block.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700722 SizeT NumNonDeadPhis = 0;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700723 InstNumberT FirstPhiNumber = Inst::NumberSentinel;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800724 for (Inst &I : Phis) {
725 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700726 continue;
727 if (FirstPhiNumber == Inst::NumberSentinel)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800728 FirstPhiNumber = I.getNumber();
729 if (I.liveness(FirstPhiNumber, Live, Liveness, LiveBegin, LiveEnd))
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700730 ++NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700731 }
732
Andrew Scull57e12682015-09-16 11:30:19 -0700733 // When using the sparse representation, after traversing the instructions in
734 // the block, the Live bitvector should only contain set bits for global
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800735 // variables upon block entry. We validate this by testing the upper bits of
736 // the Live bitvector.
737 if (Live.find_next(NumGlobalVars) != -1) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700738 if (BuildDefs::dump()) {
Andrew Scull57e12682015-09-16 11:30:19 -0700739 // This is a fatal liveness consistency error. Print some diagnostics and
740 // abort.
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700741 Ostream &Str = Func->getContext()->getStrDump();
742 Func->resetCurrentNode();
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800743 Str << "Invalid Live =";
744 for (SizeT i = NumGlobalVars; i < Live.size(); ++i) {
745 if (Live.test(i)) {
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700746 Str << " ";
747 Liveness->getVariable(i, this)->dump(Func);
748 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700749 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700750 Str << "\n";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700751 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700752 llvm::report_fatal_error("Fatal inconsistency in liveness analysis");
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700753 }
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800754 // Now truncate Live to prevent LiveIn from growing.
755 Live.resize(NumGlobalVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700756
757 bool Changed = false;
Jim Stichnoth47752552014-10-13 17:15:08 -0700758 LivenessBV &LiveIn = Liveness->getLiveIn(this);
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800759 assert(LiveIn.empty() || LiveIn.size() == NumGlobalVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700760 // Add in current LiveIn
761 Live |= LiveIn;
762 // Check result, set LiveIn=Live
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700763 SizeT &PrevNumNonDeadPhis = Liveness->getNumNonDeadPhis(this);
764 bool LiveInChanged = (Live != LiveIn);
765 Changed = (NumNonDeadPhis != PrevNumNonDeadPhis || LiveInChanged);
766 if (LiveInChanged)
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700767 LiveIn = Live;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700768 PrevNumNonDeadPhis = NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700769 return Changed;
770}
771
Jim Stichnoth230d4102015-09-25 17:40:32 -0700772// Validate the integrity of the live ranges in this block. If there are any
773// errors, it prints details and returns false. On success, it returns true.
Jim Stichnoth318f4cd2015-10-01 21:02:37 -0700774bool CfgNode::livenessValidateIntervals(Liveness *Liveness) const {
Jim Stichnoth230d4102015-09-25 17:40:32 -0700775 if (!BuildDefs::asserts())
776 return true;
777
778 // Verify there are no duplicates.
779 auto ComparePair =
780 [](const LiveBeginEndMapEntry &A, const LiveBeginEndMapEntry &B) {
781 return A.first == B.first;
782 };
783 LiveBeginEndMap &MapBegin = *Liveness->getLiveBegin(this);
784 LiveBeginEndMap &MapEnd = *Liveness->getLiveEnd(this);
785 if (std::adjacent_find(MapBegin.begin(), MapBegin.end(), ComparePair) ==
786 MapBegin.end() &&
787 std::adjacent_find(MapEnd.begin(), MapEnd.end(), ComparePair) ==
788 MapEnd.end())
789 return true;
790
791 // There is definitely a liveness error. All paths from here return false.
792 if (!BuildDefs::dump())
793 return false;
794
795 // Print all the errors.
796 if (BuildDefs::dump()) {
797 GlobalContext *Ctx = Func->getContext();
798 OstreamLocker L(Ctx);
799 Ostream &Str = Ctx->getStrDump();
800 if (Func->isVerbose()) {
801 Str << "Live range errors in the following block:\n";
802 dump(Func);
803 }
804 for (auto Start = MapBegin.begin();
805 (Start = std::adjacent_find(Start, MapBegin.end(), ComparePair)) !=
806 MapBegin.end();
807 ++Start) {
808 auto Next = Start + 1;
809 Str << "Duplicate LR begin, block " << getName() << ", instructions "
810 << Start->second << " & " << Next->second << ", variable "
Jim Stichnotha91c3412016-04-05 15:31:43 -0700811 << Liveness->getVariable(Start->first, this)->getName() << "\n";
Jim Stichnoth230d4102015-09-25 17:40:32 -0700812 }
813 for (auto Start = MapEnd.begin();
814 (Start = std::adjacent_find(Start, MapEnd.end(), ComparePair)) !=
815 MapEnd.end();
816 ++Start) {
817 auto Next = Start + 1;
818 Str << "Duplicate LR end, block " << getName() << ", instructions "
819 << Start->second << " & " << Next->second << ", variable "
Jim Stichnotha91c3412016-04-05 15:31:43 -0700820 << Liveness->getVariable(Start->first, this)->getName() << "\n";
Jim Stichnoth230d4102015-09-25 17:40:32 -0700821 }
822 }
823
824 return false;
825}
826
Andrew Scull57e12682015-09-16 11:30:19 -0700827// Once basic liveness is complete, compute actual live ranges. It is assumed
828// that within a single basic block, a live range begins at most once and ends
829// at most once. This is certainly true for pure SSA form. It is also true once
830// phis are lowered, since each assignment to the phi-based temporary is in a
831// different basic block, and there is a single read that ends the live in the
832// basic block that contained the actual phi instruction.
Jim Stichnothe5b73e62014-12-15 09:58:51 -0800833void CfgNode::livenessAddIntervals(Liveness *Liveness, InstNumberT FirstInstNum,
834 InstNumberT LastInstNum) {
835 TimerMarker T1(TimerStack::TT_liveRange, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700836
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800837 const SizeT NumVars = Liveness->getNumVarsInNode(this);
838 const LivenessBV &LiveIn = Liveness->getLiveIn(this);
839 const LivenessBV &LiveOut = Liveness->getLiveOut(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700840 LiveBeginEndMap &MapBegin = *Liveness->getLiveBegin(this);
841 LiveBeginEndMap &MapEnd = *Liveness->getLiveEnd(this);
842 std::sort(MapBegin.begin(), MapBegin.end());
843 std::sort(MapEnd.begin(), MapEnd.end());
Jim Stichnoth230d4102015-09-25 17:40:32 -0700844
845 if (!livenessValidateIntervals(Liveness)) {
846 llvm::report_fatal_error("livenessAddIntervals: Liveness error");
847 return;
848 }
Jim Stichnoth47752552014-10-13 17:15:08 -0700849
Jim Stichnoth1bdb7352016-02-29 16:58:15 -0800850 LivenessBV &LiveInAndOut = Liveness->getScratchBV();
851 LiveInAndOut = LiveIn;
Jim Stichnoth47752552014-10-13 17:15:08 -0700852 LiveInAndOut &= LiveOut;
853
854 // Iterate in parallel across the sorted MapBegin[] and MapEnd[].
855 auto IBB = MapBegin.begin(), IEB = MapEnd.begin();
856 auto IBE = MapBegin.end(), IEE = MapEnd.end();
857 while (IBB != IBE || IEB != IEE) {
858 SizeT i1 = IBB == IBE ? NumVars : IBB->first;
859 SizeT i2 = IEB == IEE ? NumVars : IEB->first;
860 SizeT i = std::min(i1, i2);
Andrew Scull57e12682015-09-16 11:30:19 -0700861 // i1 is the Variable number of the next MapBegin entry, and i2 is the
862 // Variable number of the next MapEnd entry. If i1==i2, then the Variable's
863 // live range begins and ends in this block. If i1<i2, then i1's live range
864 // begins at instruction IBB->second and extends through the end of the
865 // block. If i1>i2, then i2's live range begins at the first instruction of
866 // the block and ends at IEB->second. In any case, we choose the lesser of
867 // i1 and i2 and proceed accordingly.
Jim Stichnoth47752552014-10-13 17:15:08 -0700868 InstNumberT LB = i == i1 ? IBB->second : FirstInstNum;
869 InstNumberT LE = i == i2 ? IEB->second : LastInstNum + 1;
870
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700871 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnothf9df4522015-08-06 17:50:14 -0700872 if (LB > LE) {
Manasij Mukherjee7cd926d2016-08-04 12:33:23 -0700873 Var->addLiveRange(FirstInstNum, LE, this);
874 Var->addLiveRange(LB, LastInstNum + 1, this);
Andrew Scull57e12682015-09-16 11:30:19 -0700875 // Assert that Var is a global variable by checking that its liveness
876 // index is less than the number of globals. This ensures that the
877 // LiveInAndOut[] access is valid.
Jim Stichnothf9df4522015-08-06 17:50:14 -0700878 assert(i < Liveness->getNumGlobalVars());
879 LiveInAndOut[i] = false;
880 } else {
Manasij Mukherjee7cd926d2016-08-04 12:33:23 -0700881 Var->addLiveRange(LB, LE, this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700882 }
883 if (i == i1)
884 ++IBB;
885 if (i == i2)
886 ++IEB;
887 }
888 // Process the variables that are live across the entire block.
889 for (int i = LiveInAndOut.find_first(); i != -1;
890 i = LiveInAndOut.find_next(i)) {
891 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth552490c2015-08-05 16:21:42 -0700892 if (Liveness->getRangeMask(Var->getIndex()))
Manasij Mukherjee7cd926d2016-08-04 12:33:23 -0700893 Var->addLiveRange(FirstInstNum, LastInstNum + 1, this);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700894 }
895}
896
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700897// If this node contains only deleted instructions, and ends in an
Andrew Scull57e12682015-09-16 11:30:19 -0700898// unconditional branch, contract the node by repointing all its in-edges to
899// its successor.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700900void CfgNode::contractIfEmpty() {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800901 if (InEdges.empty())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700902 return;
Jim Stichnothae953202014-12-20 06:17:49 -0800903 Inst *Branch = nullptr;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800904 for (Inst &I : Insts) {
905 if (I.isDeleted())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700906 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800907 if (I.isUnconditionalBranch())
908 Branch = &I;
909 else if (!I.isRedundantAssign())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700910 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700911 }
Jim Stichnoth6f7ad6c2016-01-15 09:52:54 -0800912 // Make sure there is actually a successor to repoint in-edges to.
913 if (OutEdges.empty())
914 return;
Eric Holk16f80612016-04-04 17:07:42 -0700915 assert(hasSingleOutEdge());
Jim Stichnoth1921fba2015-09-15 10:06:30 -0700916 // Don't try to delete a self-loop.
917 if (OutEdges[0] == this)
918 return;
Jim Stichnoth6f7ad6c2016-01-15 09:52:54 -0800919 // Make sure the node actually contains (ends with) an unconditional branch.
920 if (Branch == nullptr)
921 return;
Jim Stichnoth1921fba2015-09-15 10:06:30 -0700922
923 Branch->setDeleted();
Andrew Scull713278a2015-07-22 17:17:02 -0700924 CfgNode *Successor = OutEdges.front();
Andrew Scull57e12682015-09-16 11:30:19 -0700925 // Repoint all this node's in-edges to this node's successor, unless this
926 // node's successor is actually itself (in which case the statement
927 // "OutEdges.front()->InEdges.push_back(Pred)" could invalidate the iterator
928 // over this->InEdges).
Andrew Scull713278a2015-07-22 17:17:02 -0700929 if (Successor != this) {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800930 for (CfgNode *Pred : InEdges) {
Andrew Scull713278a2015-07-22 17:17:02 -0700931 for (CfgNode *&I : Pred->OutEdges) {
932 if (I == this) {
933 I = Successor;
934 Successor->InEdges.push_back(Pred);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800935 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700936 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800937 for (Inst &I : Pred->getInsts()) {
938 if (!I.isDeleted())
Andrew Scull713278a2015-07-22 17:17:02 -0700939 I.repointEdges(this, Successor);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800940 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700941 }
Andrew Scull713278a2015-07-22 17:17:02 -0700942
943 // Remove the in-edge to the successor to allow node reordering to make
Andrew Scull57e12682015-09-16 11:30:19 -0700944 // better decisions. For example it's more helpful to place a node after a
945 // reachable predecessor than an unreachable one (like the one we just
Andrew Scull713278a2015-07-22 17:17:02 -0700946 // contracted).
947 Successor->InEdges.erase(
948 std::find(Successor->InEdges.begin(), Successor->InEdges.end(), this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700949 }
950 InEdges.clear();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700951}
952
Jim Stichnothff9c7062014-09-18 04:50:49 -0700953void CfgNode::doBranchOpt(const CfgNode *NextNode) {
954 TargetLowering *Target = Func->getTarget();
Andrew Scull713278a2015-07-22 17:17:02 -0700955 // Find the first opportunity for branch optimization (which will be the last
Andrew Scull57e12682015-09-16 11:30:19 -0700956 // instruction in the block) and stop. This is sufficient unless there is
957 // some target lowering where we have the possibility of multiple
958 // optimizations per block. Take care with switch lowering as there are
959 // multiple unconditional branches and only the last can be deleted.
Andrew Scull713278a2015-07-22 17:17:02 -0700960 for (Inst &I : reverse_range(Insts)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800961 if (!I.isDeleted()) {
962 Target->doBranchOpt(&I, NextNode);
Andrew Scull713278a2015-07-22 17:17:02 -0700963 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700964 }
965 }
Jim Stichnothff9c7062014-09-18 04:50:49 -0700966}
967
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700968// ======================== Dump routines ======================== //
969
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700970namespace {
971
972// Helper functions for emit().
973
974void emitRegisterUsage(Ostream &Str, const Cfg *Func, const CfgNode *Node,
Andrew Scull00741a02015-09-16 19:04:09 -0700975 bool IsLiveIn, CfgVector<SizeT> &LiveRegCount) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700976 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800977 return;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700978 Liveness *Liveness = Func->getLiveness();
979 const LivenessBV *Live;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800980 const auto StackReg = Func->getTarget()->getStackReg();
981 const auto FrameOrStackReg = Func->getTarget()->getFrameOrStackReg();
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700982 if (IsLiveIn) {
983 Live = &Liveness->getLiveIn(Node);
Jim Stichnoth751e27e2015-12-16 12:40:31 -0800984 Str << "\t\t\t\t/* LiveIn=";
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700985 } else {
986 Live = &Liveness->getLiveOut(Node);
Jim Stichnoth751e27e2015-12-16 12:40:31 -0800987 Str << "\t\t\t\t/* LiveOut=";
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700988 }
989 if (!Live->empty()) {
Andrew Scull00741a02015-09-16 19:04:09 -0700990 CfgVector<Variable *> LiveRegs;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700991 for (SizeT i = 0; i < Live->size(); ++i) {
Jim Stichnothe7418712015-10-09 06:54:02 -0700992 if (!(*Live)[i])
993 continue;
994 Variable *Var = Liveness->getVariable(i, Node);
995 if (!Var->hasReg())
996 continue;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800997 const auto RegNum = Var->getRegNum();
Jim Stichnothe7418712015-10-09 06:54:02 -0700998 if (RegNum == StackReg || RegNum == FrameOrStackReg)
999 continue;
1000 if (IsLiveIn)
1001 ++LiveRegCount[RegNum];
1002 LiveRegs.push_back(Var);
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001003 }
Andrew Scull57e12682015-09-16 11:30:19 -07001004 // Sort the variables by regnum so they are always printed in a familiar
1005 // order.
Jim Stichnoth9a05aea2015-05-26 16:01:23 -07001006 std::sort(LiveRegs.begin(), LiveRegs.end(),
1007 [](const Variable *V1, const Variable *V2) {
Jim Stichnoth8aa39662016-02-10 11:20:30 -08001008 return unsigned(V1->getRegNum()) < unsigned(V2->getRegNum());
Jim Stichnoth8e6bf6e2015-06-03 15:58:12 -07001009 });
Jim Stichnoth9a05aea2015-05-26 16:01:23 -07001010 bool First = true;
1011 for (Variable *Var : LiveRegs) {
1012 if (!First)
1013 Str << ",";
1014 First = false;
1015 Var->emit(Func);
1016 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001017 }
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001018 Str << " */\n";
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001019}
1020
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001021/// Returns true if some text was emitted - in which case the caller definitely
1022/// needs to emit a newline character.
1023bool emitLiveRangesEnded(Ostream &Str, const Cfg *Func, const Inst *Instr,
Andrew Scull00741a02015-09-16 19:04:09 -07001024 CfgVector<SizeT> &LiveRegCount) {
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001025 bool Printed = false;
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001026 if (!BuildDefs::dump())
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001027 return Printed;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001028 Variable *Dest = Instr->getDest();
Andrew Scull57e12682015-09-16 11:30:19 -07001029 // Normally we increment the live count for the dest register. But we
Jim Stichnoth230d4102015-09-25 17:40:32 -07001030 // shouldn't if the instruction's IsDestRedefined flag is set, because this
Andrew Scull57e12682015-09-16 11:30:19 -07001031 // means that the target lowering created this instruction as a non-SSA
1032 // assignment; i.e., a different, previous instruction started the dest
1033 // variable's live range.
Jim Stichnoth230d4102015-09-25 17:40:32 -07001034 if (!Instr->isDestRedefined() && Dest && Dest->hasReg())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001035 ++LiveRegCount[Dest->getRegNum()];
John Portoec3f5652015-08-31 15:07:09 -07001036 FOREACH_VAR_IN_INST(Var, *Instr) {
1037 bool ShouldReport = Instr->isLastUse(Var);
1038 if (ShouldReport && Var->hasReg()) {
1039 // Don't report end of live range until the live count reaches 0.
1040 SizeT NewCount = --LiveRegCount[Var->getRegNum()];
1041 if (NewCount)
1042 ShouldReport = false;
1043 }
1044 if (ShouldReport) {
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001045 if (Printed)
John Portoec3f5652015-08-31 15:07:09 -07001046 Str << ",";
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001047 else
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001048 Str << " \t/* END=";
John Portoec3f5652015-08-31 15:07:09 -07001049 Var->emit(Func);
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001050 Printed = true;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001051 }
1052 }
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001053 if (Printed)
1054 Str << " */";
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001055 return Printed;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001056}
1057
Jan Voung0faec4c2014-11-05 17:29:56 -08001058void updateStats(Cfg *Func, const Inst *I) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001059 if (!BuildDefs::dump())
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001060 return;
Andrew Scull57e12682015-09-16 11:30:19 -07001061 // Update emitted instruction count, plus fill/spill count for Variable
1062 // operands without a physical register.
Jan Voung0faec4c2014-11-05 17:29:56 -08001063 if (uint32_t Count = I->getEmitInstCount()) {
1064 Func->getContext()->statsUpdateEmitted(Count);
1065 if (Variable *Dest = I->getDest()) {
1066 if (!Dest->hasReg())
1067 Func->getContext()->statsUpdateFills();
1068 }
1069 for (SizeT S = 0; S < I->getSrcSize(); ++S) {
Jim Stichnoth54f3d512015-12-11 09:53:00 -08001070 if (auto *Src = llvm::dyn_cast<Variable>(I->getSrc(S))) {
Jan Voung0faec4c2014-11-05 17:29:56 -08001071 if (!Src->hasReg())
1072 Func->getContext()->statsUpdateSpills();
1073 }
1074 }
1075 }
1076}
1077
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001078} // end of anonymous namespace
1079
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001080void CfgNode::emit(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001081 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -08001082 return;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001083 Func->setCurrentNode(this);
1084 Ostream &Str = Func->getContext()->getStrEmit();
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001085 Liveness *Liveness = Func->getLiveness();
Karl Schimpfd4699942016-04-02 09:55:31 -07001086 const bool DecorateAsm = Liveness && getFlags().getDecorateAsm();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001087 Str << getAsmName() << ":\n";
Andrew Scull57e12682015-09-16 11:30:19 -07001088 // LiveRegCount keeps track of the number of currently live variables that
1089 // each register is assigned to. Normally that would be only 0 or 1, but the
1090 // register allocator's AllowOverlap inference allows it to be greater than 1
1091 // for short periods.
Andrew Scull00741a02015-09-16 19:04:09 -07001092 CfgVector<SizeT> LiveRegCount(Func->getTarget()->getNumRegisters());
Jim Stichnoth4175b2a2015-04-30 12:26:22 -07001093 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -07001094 constexpr bool IsLiveIn = true;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -07001095 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
Jim Stichnoth238b4c12015-10-01 07:46:38 -07001096 if (getInEdges().size()) {
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001097 Str << "\t\t\t\t/* preds=";
Jim Stichnoth238b4c12015-10-01 07:46:38 -07001098 bool First = true;
1099 for (CfgNode *I : getInEdges()) {
1100 if (!First)
1101 Str << ",";
1102 First = false;
Jim Stichnoth9a63bab2015-10-05 11:13:59 -07001103 Str << "$" << I->getName();
Jim Stichnoth238b4c12015-10-01 07:46:38 -07001104 }
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001105 Str << " */\n";
Jim Stichnoth238b4c12015-10-01 07:46:38 -07001106 }
1107 if (getLoopNestDepth()) {
Jim Stichnoth751e27e2015-12-16 12:40:31 -08001108 Str << "\t\t\t\t/* loop depth=" << getLoopNestDepth() << " */\n";
Jim Stichnoth238b4c12015-10-01 07:46:38 -07001109 }
Jim Stichnoth4175b2a2015-04-30 12:26:22 -07001110 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001111
Jim Stichnoth29841e82014-12-23 12:26:24 -08001112 for (const Inst &I : Phis) {
1113 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001114 continue;
1115 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -08001116 I.emit(Func);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001117 }
Jim Stichnoth29841e82014-12-23 12:26:24 -08001118 for (const Inst &I : Insts) {
1119 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001120 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -07001121 if (I.isRedundantAssign()) {
Andrew Scull57e12682015-09-16 11:30:19 -07001122 // Usually, redundant assignments end the live range of the src variable
1123 // and begin the live range of the dest variable, with no net effect on
1124 // the liveness of their register. However, if the register allocator
1125 // infers the AllowOverlap condition, then this may be a redundant
1126 // assignment that does not end the src variable's live range, in which
1127 // case the active variable count for that register needs to be bumped.
1128 // That normally would have happened as part of emitLiveRangesEnded(),
1129 // but that isn't called for redundant assignments.
Jim Stichnothb82baf22015-05-27 10:41:07 -07001130 Variable *Dest = I.getDest();
Jim Stichnoth1fb030c2015-10-15 11:10:38 -07001131 if (DecorateAsm && Dest->hasReg()) {
Jim Stichnothb82baf22015-05-27 10:41:07 -07001132 ++LiveRegCount[Dest->getRegNum()];
Jim Stichnoth1fb030c2015-10-15 11:10:38 -07001133 if (I.isLastUse(I.getSrc(0)))
1134 --LiveRegCount[llvm::cast<Variable>(I.getSrc(0))->getRegNum()];
1135 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -07001136 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -07001137 }
Jim Stichnoth29841e82014-12-23 12:26:24 -08001138 I.emit(Func);
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001139 bool Printed = false;
Jan Voung0faec4c2014-11-05 17:29:56 -08001140 if (DecorateAsm)
Jim Stichnoth3e859b72015-11-10 14:39:51 -08001141 Printed = emitLiveRangesEnded(Str, Func, &I, LiveRegCount);
1142 if (Printed || llvm::isa<InstTarget>(&I))
1143 Str << "\n";
Jim Stichnoth29841e82014-12-23 12:26:24 -08001144 updateStats(Func, &I);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001145 }
Jim Stichnoth4175b2a2015-04-30 12:26:22 -07001146 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -07001147 constexpr bool IsLiveIn = false;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -07001148 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
1149 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -07001150}
1151
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001152// Helper class for emitIAS().
1153namespace {
1154class BundleEmitHelper {
1155 BundleEmitHelper() = delete;
1156 BundleEmitHelper(const BundleEmitHelper &) = delete;
1157 BundleEmitHelper &operator=(const BundleEmitHelper &) = delete;
1158
1159public:
David Sehr26217e32015-11-26 13:03:50 -08001160 BundleEmitHelper(Assembler *Asm, const InstList &Insts)
1161 : Asm(Asm), End(Insts.end()), BundleLockStart(End),
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001162 BundleSize(1 << Asm->getBundleAlignLog2Bytes()),
Jim Stichnotheafb56c2015-06-22 10:35:22 -07001163 BundleMaskLo(BundleSize - 1), BundleMaskHi(~BundleMaskLo) {}
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001164 // Check whether we're currently within a bundle_lock region.
1165 bool isInBundleLockRegion() const { return BundleLockStart != End; }
Andrew Scull57e12682015-09-16 11:30:19 -07001166 // Check whether the current bundle_lock region has the align_to_end option.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001167 bool isAlignToEnd() const {
1168 assert(isInBundleLockRegion());
1169 return llvm::cast<InstBundleLock>(getBundleLockStart())->getOption() ==
1170 InstBundleLock::Opt_AlignToEnd;
1171 }
John Porto56958cb2016-01-14 09:18:18 -08001172 bool isPadToEnd() const {
1173 assert(isInBundleLockRegion());
1174 return llvm::cast<InstBundleLock>(getBundleLockStart())->getOption() ==
1175 InstBundleLock::Opt_PadToEnd;
1176 }
Andrew Scull57e12682015-09-16 11:30:19 -07001177 // Check whether the entire bundle_lock region falls within the same bundle.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001178 bool isSameBundle() const {
1179 assert(isInBundleLockRegion());
1180 return SizeSnapshotPre == SizeSnapshotPost ||
1181 (SizeSnapshotPre & BundleMaskHi) ==
1182 ((SizeSnapshotPost - 1) & BundleMaskHi);
1183 }
Andrew Scull57e12682015-09-16 11:30:19 -07001184 // Get the bundle alignment of the first instruction of the bundle_lock
1185 // region.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001186 intptr_t getPreAlignment() const {
1187 assert(isInBundleLockRegion());
1188 return SizeSnapshotPre & BundleMaskLo;
1189 }
Andrew Scull57e12682015-09-16 11:30:19 -07001190 // Get the bundle alignment of the first instruction past the bundle_lock
1191 // region.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001192 intptr_t getPostAlignment() const {
1193 assert(isInBundleLockRegion());
1194 return SizeSnapshotPost & BundleMaskLo;
1195 }
Andrew Scull57e12682015-09-16 11:30:19 -07001196 // Get the iterator pointing to the bundle_lock instruction, e.g. to roll
1197 // back the instruction iteration to that point.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001198 InstList::const_iterator getBundleLockStart() const {
1199 assert(isInBundleLockRegion());
1200 return BundleLockStart;
1201 }
Andrew Scull57e12682015-09-16 11:30:19 -07001202 // Set up bookkeeping when the bundle_lock instruction is first processed.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001203 void enterBundleLock(InstList::const_iterator I) {
1204 assert(!isInBundleLockRegion());
1205 BundleLockStart = I;
1206 SizeSnapshotPre = Asm->getBufferSize();
1207 Asm->setPreliminary(true);
1208 assert(isInBundleLockRegion());
1209 }
Andrew Scull57e12682015-09-16 11:30:19 -07001210 // Update bookkeeping when the bundle_unlock instruction is processed.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001211 void enterBundleUnlock() {
1212 assert(isInBundleLockRegion());
1213 SizeSnapshotPost = Asm->getBufferSize();
1214 }
Andrew Scull57e12682015-09-16 11:30:19 -07001215 // Update bookkeeping when we are completely finished with the bundle_lock
1216 // region.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001217 void leaveBundleLockRegion() { BundleLockStart = End; }
Andrew Scull57e12682015-09-16 11:30:19 -07001218 // Check whether the instruction sequence fits within the current bundle, and
1219 // if not, add nop padding to the end of the current bundle.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001220 void padToNextBundle() {
1221 assert(isInBundleLockRegion());
1222 if (!isSameBundle()) {
1223 intptr_t PadToNextBundle = BundleSize - getPreAlignment();
1224 Asm->padWithNop(PadToNextBundle);
1225 SizeSnapshotPre += PadToNextBundle;
1226 SizeSnapshotPost += PadToNextBundle;
1227 assert((Asm->getBufferSize() & BundleMaskLo) == 0);
1228 assert(Asm->getBufferSize() == SizeSnapshotPre);
1229 }
1230 }
Andrew Scull57e12682015-09-16 11:30:19 -07001231 // If align_to_end is specified, add padding such that the instruction
1232 // sequences ends precisely at a bundle boundary.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001233 void padForAlignToEnd() {
1234 assert(isInBundleLockRegion());
1235 if (isAlignToEnd()) {
1236 if (intptr_t Offset = getPostAlignment()) {
1237 Asm->padWithNop(BundleSize - Offset);
1238 SizeSnapshotPre = Asm->getBufferSize();
1239 }
1240 }
1241 }
John Porto56958cb2016-01-14 09:18:18 -08001242 // If pad_to_end is specified, add padding such that the first instruction
1243 // after the instruction sequence starts at a bundle boundary.
1244 void padForPadToEnd() {
1245 assert(isInBundleLockRegion());
1246 if (isPadToEnd()) {
1247 if (intptr_t Offset = getPostAlignment()) {
1248 Asm->padWithNop(BundleSize - Offset);
1249 SizeSnapshotPre = Asm->getBufferSize();
1250 }
1251 }
1252 } // Update bookkeeping when rolling back for the second pass.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001253 void rollback() {
1254 assert(isInBundleLockRegion());
1255 Asm->setBufferSize(SizeSnapshotPre);
1256 Asm->setPreliminary(false);
1257 }
1258
1259private:
1260 Assembler *const Asm;
Andrew Scull57e12682015-09-16 11:30:19 -07001261 // End is a sentinel value such that BundleLockStart==End implies that we are
1262 // not in a bundle_lock region.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001263 const InstList::const_iterator End;
1264 InstList::const_iterator BundleLockStart;
1265 const intptr_t BundleSize;
1266 // Masking with BundleMaskLo identifies an address's bundle offset.
1267 const intptr_t BundleMaskLo;
1268 // Masking with BundleMaskHi identifies an address's bundle.
1269 const intptr_t BundleMaskHi;
Jim Stichnotheafb56c2015-06-22 10:35:22 -07001270 intptr_t SizeSnapshotPre = 0;
1271 intptr_t SizeSnapshotPost = 0;
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001272};
1273
1274} // end of anonymous namespace
1275
Jan Voung0faec4c2014-11-05 17:29:56 -08001276void CfgNode::emitIAS(Cfg *Func) const {
1277 Func->setCurrentNode(this);
Jim Stichnothbbca7542015-02-11 16:08:31 -08001278 Assembler *Asm = Func->getAssembler<>();
Andrew Scull57e12682015-09-16 11:30:19 -07001279 // TODO(stichnot): When sandboxing, defer binding the node label until just
1280 // before the first instruction is emitted, to reduce the chance that a
1281 // padding nop is a branch target.
Karl Schimpf50a33312015-10-23 09:19:48 -07001282 Asm->bindCfgNodeLabel(this);
Jim Stichnoth29841e82014-12-23 12:26:24 -08001283 for (const Inst &I : Phis) {
1284 if (I.isDeleted())
Jan Voung0faec4c2014-11-05 17:29:56 -08001285 continue;
1286 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -08001287 I.emitIAS(Func);
Jan Voung0faec4c2014-11-05 17:29:56 -08001288 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001289
1290 // Do the simple emission if not sandboxed.
Karl Schimpfd4699942016-04-02 09:55:31 -07001291 if (!getFlags().getUseSandboxing()) {
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001292 for (const Inst &I : Insts) {
1293 if (!I.isDeleted() && !I.isRedundantAssign()) {
1294 I.emitIAS(Func);
1295 updateStats(Func, &I);
1296 }
1297 }
1298 return;
Jan Voung0faec4c2014-11-05 17:29:56 -08001299 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001300
Andrew Scull57e12682015-09-16 11:30:19 -07001301 // The remainder of the function handles emission with sandboxing. There are
1302 // explicit bundle_lock regions delimited by bundle_lock and bundle_unlock
1303 // instructions. All other instructions are treated as an implicit
1304 // one-instruction bundle_lock region. Emission is done twice for each
1305 // bundle_lock region. The first pass is a preliminary pass, after which we
1306 // can figure out what nop padding is needed, then roll back, and make the
1307 // final pass.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001308 //
Andrew Scull57e12682015-09-16 11:30:19 -07001309 // Ideally, the first pass would be speculative and the second pass would
1310 // only be done if nop padding were needed, but the structure of the
1311 // integrated assembler makes it hard to roll back the state of label
1312 // bindings, label links, and relocation fixups. Instead, the first pass just
1313 // disables all mutation of that state.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001314
David Sehr26217e32015-11-26 13:03:50 -08001315 BundleEmitHelper Helper(Asm, Insts);
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001316 InstList::const_iterator End = Insts.end();
Andrew Scull57e12682015-09-16 11:30:19 -07001317 // Retrying indicates that we had to roll back to the bundle_lock instruction
1318 // to apply padding before the bundle_lock sequence.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001319 bool Retrying = false;
1320 for (InstList::const_iterator I = Insts.begin(); I != End; ++I) {
1321 if (I->isDeleted() || I->isRedundantAssign())
1322 continue;
1323
1324 if (llvm::isa<InstBundleLock>(I)) {
Andrew Scull57e12682015-09-16 11:30:19 -07001325 // Set up the initial bundle_lock state. This should not happen while
1326 // retrying, because the retry rolls back to the instruction following
1327 // the bundle_lock instruction.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001328 assert(!Retrying);
1329 Helper.enterBundleLock(I);
1330 continue;
1331 }
1332
1333 if (llvm::isa<InstBundleUnlock>(I)) {
1334 Helper.enterBundleUnlock();
1335 if (Retrying) {
1336 // Make sure all instructions are in the same bundle.
1337 assert(Helper.isSameBundle());
Andrew Scull57e12682015-09-16 11:30:19 -07001338 // If align_to_end is specified, make sure the next instruction begins
1339 // the bundle.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001340 assert(!Helper.isAlignToEnd() || Helper.getPostAlignment() == 0);
John Porto56958cb2016-01-14 09:18:18 -08001341 Helper.padForPadToEnd();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001342 Helper.leaveBundleLockRegion();
1343 Retrying = false;
1344 } else {
1345 // This is the first pass, so roll back for the retry pass.
1346 Helper.rollback();
Andrew Scull57e12682015-09-16 11:30:19 -07001347 // Pad to the next bundle if the instruction sequence crossed a bundle
1348 // boundary.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001349 Helper.padToNextBundle();
1350 // Insert additional padding to make AlignToEnd work.
1351 Helper.padForAlignToEnd();
1352 // Prepare for the retry pass after padding is done.
1353 Retrying = true;
1354 I = Helper.getBundleLockStart();
1355 }
1356 continue;
1357 }
1358
1359 // I points to a non bundle_lock/bundle_unlock instruction.
1360 if (Helper.isInBundleLockRegion()) {
1361 I->emitIAS(Func);
1362 // Only update stats during the final pass.
1363 if (Retrying)
Jim Stichnothf5fdd232016-05-09 12:24:36 -07001364 updateStats(Func, iteratorToInst(I));
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001365 } else {
1366 // Treat it as though there were an implicit bundle_lock and
1367 // bundle_unlock wrapping the instruction.
1368 Helper.enterBundleLock(I);
1369 I->emitIAS(Func);
1370 Helper.enterBundleUnlock();
1371 Helper.rollback();
1372 Helper.padToNextBundle();
1373 I->emitIAS(Func);
Jim Stichnothf5fdd232016-05-09 12:24:36 -07001374 updateStats(Func, iteratorToInst(I));
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001375 Helper.leaveBundleLockRegion();
1376 }
1377 }
1378
Andrew Scull57e12682015-09-16 11:30:19 -07001379 // Don't allow bundle locking across basic blocks, to keep the backtracking
1380 // mechanism simple.
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001381 assert(!Helper.isInBundleLockRegion());
1382 assert(!Retrying);
Jan Voung0faec4c2014-11-05 17:29:56 -08001383}
1384
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001385void CfgNode::dump(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001386 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -08001387 return;
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001388 Func->setCurrentNode(this);
1389 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001390 Liveness *Liveness = Func->getLiveness();
Andrew Scullaa6c1092015-09-03 17:50:30 -07001391 if (Func->isVerbose(IceV_Instructions) || Func->isVerbose(IceV_Loop))
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001392 Str << getName() << ":\n";
Andrew Scullaa6c1092015-09-03 17:50:30 -07001393 // Dump the loop nest depth
1394 if (Func->isVerbose(IceV_Loop))
1395 Str << " // LoopNestDepth = " << getLoopNestDepth() << "\n";
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001396 // Dump list of predecessor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001397 if (Func->isVerbose(IceV_Preds) && !InEdges.empty()) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001398 Str << " // preds = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001399 bool First = true;
1400 for (CfgNode *I : InEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001401 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001402 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001403 First = false;
1404 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001405 }
1406 Str << "\n";
1407 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001408 // Dump the live-in variables.
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001409 if (Func->isVerbose(IceV_Liveness)) {
1410 if (Liveness != nullptr && !Liveness->getLiveIn(this).empty()) {
1411 const LivenessBV &LiveIn = Liveness->getLiveIn(this);
1412 Str << " // LiveIn:";
1413 for (SizeT i = 0; i < LiveIn.size(); ++i) {
1414 if (LiveIn[i]) {
1415 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnotha91c3412016-04-05 15:31:43 -07001416 Str << " %" << Var->getName();
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001417 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
1418 Str << ":"
1419 << Func->getTarget()->getRegName(Var->getRegNum(),
1420 Var->getType());
1421 }
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001422 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001423 }
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001424 Str << "\n";
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001425 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001426 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001427 // Dump each instruction.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001428 if (Func->isVerbose(IceV_Instructions)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -08001429 for (const Inst &I : Phis)
1430 I.dumpDecorated(Func);
1431 for (const Inst &I : Insts)
1432 I.dumpDecorated(Func);
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001433 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001434 // Dump the live-out variables.
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001435 if (Func->isVerbose(IceV_Liveness)) {
1436 if (Liveness != nullptr && !Liveness->getLiveOut(this).empty()) {
1437 const LivenessBV &LiveOut = Liveness->getLiveOut(this);
1438 Str << " // LiveOut:";
1439 for (SizeT i = 0; i < LiveOut.size(); ++i) {
1440 if (LiveOut[i]) {
1441 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnotha91c3412016-04-05 15:31:43 -07001442 Str << " %" << Var->getName();
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001443 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
1444 Str << ":"
1445 << Func->getTarget()->getRegName(Var->getRegNum(),
1446 Var->getType());
1447 }
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001448 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001449 }
Jim Stichnoth1bdb7352016-02-29 16:58:15 -08001450 Str << "\n";
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001451 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001452 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001453 // Dump list of successor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001454 if (Func->isVerbose(IceV_Succs)) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001455 Str << " // succs = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001456 bool First = true;
1457 for (CfgNode *I : OutEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001458 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001459 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001460 First = false;
1461 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001462 }
1463 Str << "\n";
1464 }
1465}
1466
John Portof8b4cc82015-06-09 18:06:19 -07001467void CfgNode::profileExecutionCount(VariableDeclaration *Var) {
Jim Stichnoth467ffe52016-03-29 15:01:06 -07001468 GlobalContext *Ctx = Func->getContext();
1469 GlobalString RMW_I64 = Ctx->getGlobalString("llvm.nacl.atomic.rmw.i64");
John Portof8b4cc82015-06-09 18:06:19 -07001470
1471 bool BadIntrinsic = false;
1472 const Intrinsics::FullIntrinsicInfo *Info =
Jim Stichnoth467ffe52016-03-29 15:01:06 -07001473 Ctx->getIntrinsicsInfo().find(RMW_I64, BadIntrinsic);
John Portof8b4cc82015-06-09 18:06:19 -07001474 assert(!BadIntrinsic);
1475 assert(Info != nullptr);
1476
Jim Stichnoth467ffe52016-03-29 15:01:06 -07001477 Operand *RMWI64Name = Ctx->getConstantExternSym(RMW_I64);
John Porto8b1a7052015-06-17 13:20:08 -07001478 constexpr RelocOffsetT Offset = 0;
Jim Stichnoth467ffe52016-03-29 15:01:06 -07001479 Constant *Counter = Ctx->getConstantSym(Offset, Var->getName());
1480 Constant *AtomicRMWOp = Ctx->getConstantInt32(Intrinsics::AtomicAdd);
1481 Constant *One = Ctx->getConstantInt64(1);
John Portof8b4cc82015-06-09 18:06:19 -07001482 Constant *OrderAcquireRelease =
Jim Stichnoth467ffe52016-03-29 15:01:06 -07001483 Ctx->getConstantInt32(Intrinsics::MemoryOrderAcquireRelease);
John Portof8b4cc82015-06-09 18:06:19 -07001484
Jim Stichnoth8cfeb692016-02-05 09:50:02 -08001485 auto *Instr = InstIntrinsicCall::create(
John Portof8b4cc82015-06-09 18:06:19 -07001486 Func, 5, Func->makeVariable(IceType_i64), RMWI64Name, Info->Info);
Jim Stichnoth8cfeb692016-02-05 09:50:02 -08001487 Instr->addArg(AtomicRMWOp);
1488 Instr->addArg(Counter);
1489 Instr->addArg(One);
1490 Instr->addArg(OrderAcquireRelease);
1491 Insts.push_front(Instr);
John Portof8b4cc82015-06-09 18:06:19 -07001492}
1493
Manasij Mukherjee45f51a22016-06-27 16:12:37 -07001494void CfgNode::removeInEdge(CfgNode *In) {
1495 InEdges.erase(std::find(InEdges.begin(), InEdges.end(), In));
1496}
1497
1498CfgNode *CfgNode::shortCircuit() {
1499 auto *Func = getCfg();
1500 auto *Last = &getInsts().back();
1501 Variable *Condition = nullptr;
1502 InstBr *Br = nullptr;
1503 if ((Br = llvm::dyn_cast<InstBr>(Last))) {
1504 if (!Br->isUnconditional()) {
1505 Condition = llvm::dyn_cast<Variable>(Br->getCondition());
1506 }
1507 }
1508 if (Condition == nullptr)
1509 return nullptr;
1510
1511 auto *JumpOnTrue = Br->getTargetTrue();
1512 auto *JumpOnFalse = Br->getTargetFalse();
1513
1514 bool FoundOr = false;
1515 bool FoundAnd = false;
1516
1517 InstArithmetic *TopLevelBoolOp = nullptr;
1518
1519 for (auto &Inst : reverse_range(getInsts())) {
1520 if (Inst.isDeleted())
1521 continue;
1522 if (Inst.getDest() == Condition) {
1523 if (auto *Arith = llvm::dyn_cast<InstArithmetic>(&Inst)) {
1524
1525 FoundOr = (Arith->getOp() == InstArithmetic::OpKind::Or);
1526 FoundAnd = (Arith->getOp() == InstArithmetic::OpKind::And);
1527
1528 if (FoundOr || FoundAnd) {
1529 TopLevelBoolOp = Arith;
1530 break;
1531 }
1532 }
1533 }
1534 }
1535
1536 if (!TopLevelBoolOp)
1537 return nullptr;
1538
1539 auto IsOperand = [](Inst *Instr, Operand *Opr) -> bool {
1540 for (SizeT i = 0; i < Instr->getSrcSize(); ++i) {
1541 if (Instr->getSrc(i) == Opr)
1542 return true;
1543 }
1544 return false;
1545 };
1546 Inst *FirstOperandDef = nullptr;
1547 for (auto &Inst : getInsts()) {
1548 if (IsOperand(TopLevelBoolOp, Inst.getDest())) {
1549 FirstOperandDef = &Inst;
1550 break;
1551 }
1552 }
1553
1554 if (FirstOperandDef == nullptr) {
1555 return nullptr;
1556 }
1557
1558 // Check for side effects
1559 auto It = Ice::instToIterator(FirstOperandDef);
1560 while (It != getInsts().end()) {
1561 if (It->isDeleted()) {
1562 ++It;
1563 continue;
1564 }
1565 if (llvm::isa<InstBr>(It) || llvm::isa<InstRet>(It)) {
1566 break;
1567 }
1568 auto *Dest = It->getDest();
1569 if (It->getDest() == nullptr || It->hasSideEffects() ||
1570 !Func->getVMetadata()->isSingleBlock(Dest)) {
1571 // Relying on short cicuit eval here.
1572 // getVMetadata()->isSingleBlock(Dest)
1573 // will segfault if It->getDest() == nullptr
1574 return nullptr;
1575 }
1576 It++;
1577 }
1578
1579 auto *NewNode = Func->makeNode();
1580 NewNode->setLoopNestDepth(getLoopNestDepth());
1581 It = Ice::instToIterator(FirstOperandDef);
1582 It++; // Have to split after the def
1583
1584 NewNode->getInsts().splice(NewNode->getInsts().begin(), getInsts(), It,
1585 getInsts().end());
1586
1587 if (BuildDefs::dump()) {
1588 NewNode->setName(getName().append("_2"));
1589 setName(getName().append("_1"));
1590 }
1591
1592 // Point edges properly
1593 NewNode->addInEdge(this);
1594 for (auto *Out : getOutEdges()) {
1595 NewNode->addOutEdge(Out);
1596 Out->addInEdge(NewNode);
1597 }
1598 removeAllOutEdges();
1599 addOutEdge(NewNode);
1600
1601 // Manage Phi instructions of successors
1602 for (auto *Succ : NewNode->getOutEdges()) {
1603 for (auto &Inst : Succ->getPhis()) {
1604 auto *Phi = llvm::cast<InstPhi>(&Inst);
1605 for (SizeT i = 0; i < Phi->getSrcSize(); ++i) {
1606 if (Phi->getLabel(i) == this) {
1607 Phi->addArgument(Phi->getSrc(i), NewNode);
1608 }
1609 }
1610 }
1611 }
1612
1613 // Create new Br instruction
1614 InstBr *NewInst = nullptr;
1615 if (FoundOr) {
1616 addOutEdge(JumpOnTrue);
1617 JumpOnFalse->removeInEdge(this);
1618 NewInst =
1619 InstBr::create(Func, FirstOperandDef->getDest(), JumpOnTrue, NewNode);
1620 } else if (FoundAnd) {
1621 addOutEdge(JumpOnFalse);
1622 JumpOnTrue->removeInEdge(this);
1623 NewInst =
1624 InstBr::create(Func, FirstOperandDef->getDest(), NewNode, JumpOnFalse);
1625 } else {
1626 return nullptr;
1627 }
1628
1629 assert(NewInst != nullptr);
1630 appendInst(NewInst);
1631
1632 Operand *UnusedOperand = nullptr;
1633 assert(TopLevelBoolOp->getSrcSize() == 2);
1634 if (TopLevelBoolOp->getSrc(0) == FirstOperandDef->getDest())
1635 UnusedOperand = TopLevelBoolOp->getSrc(1);
1636 else if (TopLevelBoolOp->getSrc(1) == FirstOperandDef->getDest())
1637 UnusedOperand = TopLevelBoolOp->getSrc(0);
1638 assert(UnusedOperand);
1639
1640 Br->replaceSource(0, UnusedOperand); // Index 0 has the condition of the Br
1641
1642 TopLevelBoolOp->setDeleted();
1643 return NewNode;
1644}
1645
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001646} // end of namespace Ice