Selection DAG preprocessing on Hexagon
[oota-llvm.git] / lib / Target / Hexagon / HexagonISelDAGToDAG.cpp
1 //===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the Hexagon target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Hexagon.h"
15 #include "HexagonISelLowering.h"
16 #include "HexagonTargetMachine.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/CodeGen/SelectionDAGISel.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24
25 #define DEBUG_TYPE "hexagon-isel"
26
27 static
28 cl::opt<unsigned>
29 MaxNumOfUsesForConstExtenders("ga-max-num-uses-for-constant-extenders",
30   cl::Hidden, cl::init(2),
31   cl::desc("Maximum number of uses of a global address such that we still us a"
32            "constant extended instruction"));
33
34 //===----------------------------------------------------------------------===//
35 // Instruction Selector Implementation
36 //===----------------------------------------------------------------------===//
37
38 namespace llvm {
39   void initializeHexagonDAGToDAGISelPass(PassRegistry&);
40 }
41
42 //===--------------------------------------------------------------------===//
43 /// HexagonDAGToDAGISel - Hexagon specific code to select Hexagon machine
44 /// instructions for SelectionDAG operations.
45 ///
46 namespace {
47 class HexagonDAGToDAGISel : public SelectionDAGISel {
48   const HexagonTargetMachine& HTM;
49   const HexagonSubtarget &HST;
50 public:
51   explicit HexagonDAGToDAGISel(HexagonTargetMachine &tm,
52                                CodeGenOpt::Level OptLevel)
53       : SelectionDAGISel(tm, OptLevel), HTM(tm),
54         HST(tm.getSubtarget<HexagonSubtarget>()) {
55     initializeHexagonDAGToDAGISelPass(*PassRegistry::getPassRegistry());
56   }
57   virtual void PreprocessISelDAG() override;
58
59   SDNode *Select(SDNode *N) override;
60
61   // Complex Pattern Selectors.
62   inline bool SelectAddrGA(SDValue &N, SDValue &R);
63   inline bool SelectAddrGP(SDValue &N, SDValue &R);
64   bool SelectGlobalAddress(SDValue &N, SDValue &R, bool UseGP);
65   bool SelectAddrFI(SDValue &N, SDValue &R);
66
67   const char *getPassName() const override {
68     return "Hexagon DAG->DAG Pattern Instruction Selection";
69   }
70
71   SDNode *SelectFrameIndex(SDNode *N);
72   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
73   /// inline asm expressions.
74   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
75                                     unsigned ConstraintID,
76                                     std::vector<SDValue> &OutOps) override;
77   SDNode *SelectLoad(SDNode *N);
78   SDNode *SelectBaseOffsetLoad(LoadSDNode *LD, SDLoc dl);
79   SDNode *SelectIndexedLoad(LoadSDNode *LD, SDLoc dl);
80   SDNode *SelectIndexedLoadZeroExtend64(LoadSDNode *LD, unsigned Opcode,
81                                         SDLoc dl);
82   SDNode *SelectIndexedLoadSignExtend64(LoadSDNode *LD, unsigned Opcode,
83                                         SDLoc dl);
84   SDNode *SelectBaseOffsetStore(StoreSDNode *ST, SDLoc dl);
85   SDNode *SelectIndexedStore(StoreSDNode *ST, SDLoc dl);
86   SDNode *SelectStore(SDNode *N);
87   SDNode *SelectSHL(SDNode *N);
88   SDNode *SelectSelect(SDNode *N);
89   SDNode *SelectTruncate(SDNode *N);
90   SDNode *SelectMul(SDNode *N);
91   SDNode *SelectZeroExtend(SDNode *N);
92   SDNode *SelectIntrinsicWChain(SDNode *N);
93   SDNode *SelectIntrinsicWOChain(SDNode *N);
94   SDNode *SelectConstant(SDNode *N);
95   SDNode *SelectConstantFP(SDNode *N);
96   SDNode *SelectAdd(SDNode *N);
97
98   // XformMskToBitPosU5Imm - Returns the bit position which
99   // the single bit 32 bit mask represents.
100   // Used in Clr and Set bit immediate memops.
101   SDValue XformMskToBitPosU5Imm(uint32_t Imm) {
102     int32_t bitPos;
103     bitPos = Log2_32(Imm);
104     assert(bitPos >= 0 && bitPos < 32 &&
105            "Constant out of range for 32 BitPos Memops");
106     return CurDAG->getTargetConstant(bitPos, MVT::i32);
107   }
108
109   // XformMskToBitPosU4Imm - Returns the bit position which the single-bit
110   // 16 bit mask represents. Used in Clr and Set bit immediate memops.
111   SDValue XformMskToBitPosU4Imm(uint16_t Imm) {
112     return XformMskToBitPosU5Imm(Imm);
113   }
114
115   // XformMskToBitPosU3Imm - Returns the bit position which the single-bit
116   // 8 bit mask represents. Used in Clr and Set bit immediate memops.
117   SDValue XformMskToBitPosU3Imm(uint8_t Imm) {
118     return XformMskToBitPosU5Imm(Imm);
119   }
120
121   // Return true if there is exactly one bit set in V, i.e., if V is one of the
122   // following integers: 2^0, 2^1, ..., 2^31.
123   bool ImmIsSingleBit(uint32_t v) const {
124     return isPowerOf2_32(v);
125   }
126
127   // XformM5ToU5Imm - Return a target constant with the specified value, of
128   // type i32 where the negative literal is transformed into a positive literal
129   // for use in -= memops.
130   inline SDValue XformM5ToU5Imm(signed Imm) {
131      assert( (Imm >= -31 && Imm <= -1)  && "Constant out of range for Memops");
132      return CurDAG->getTargetConstant( - Imm, MVT::i32);
133   }
134
135   // XformU7ToU7M1Imm - Return a target constant decremented by 1, in range
136   // [1..128], used in cmpb.gtu instructions.
137   inline SDValue XformU7ToU7M1Imm(signed Imm) {
138     assert((Imm >= 1 && Imm <= 128) && "Constant out of range for cmpb op");
139     return CurDAG->getTargetConstant(Imm - 1, MVT::i8);
140   }
141
142   // XformS8ToS8M1Imm - Return a target constant decremented by 1.
143   inline SDValue XformSToSM1Imm(signed Imm) {
144     return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
145   }
146
147   // XformU8ToU8M1Imm - Return a target constant decremented by 1.
148   inline SDValue XformUToUM1Imm(unsigned Imm) {
149     assert((Imm >= 1) && "Cannot decrement unsigned int less than 1");
150     return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
151   }
152
153   // XformSToSM2Imm - Return a target constant decremented by 2.
154   inline SDValue XformSToSM2Imm(unsigned Imm) {
155     return CurDAG->getTargetConstant(Imm - 2, MVT::i32);
156   }
157
158   // XformSToSM3Imm - Return a target constant decremented by 3.
159   inline SDValue XformSToSM3Imm(unsigned Imm) {
160     return CurDAG->getTargetConstant(Imm - 3, MVT::i32);
161   }
162
163   // Include the pieces autogenerated from the target description.
164   #include "HexagonGenDAGISel.inc"
165
166 private:
167   bool isValueExtension(const SDValue &Val, unsigned FromBits, SDValue &Src);
168 }; // end HexagonDAGToDAGISel
169 }  // end anonymous namespace
170
171
172 /// createHexagonISelDag - This pass converts a legalized DAG into a
173 /// Hexagon-specific DAG, ready for instruction scheduling.
174 ///
175 namespace llvm {
176 FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
177                                    CodeGenOpt::Level OptLevel) {
178   return new HexagonDAGToDAGISel(TM, OptLevel);
179 }
180 }
181
182 static void initializePassOnce(PassRegistry &Registry) {
183   const char *Name = "Hexagon DAG->DAG Pattern Instruction Selection";
184   PassInfo *PI = new PassInfo(Name, "hexagon-isel",
185                               &SelectionDAGISel::ID, nullptr, false, false);
186   Registry.registerPass(*PI, true);
187 }
188
189 void llvm::initializeHexagonDAGToDAGISelPass(PassRegistry &Registry) {
190   CALL_ONCE_INITIALIZATION(initializePassOnce)
191 }
192
193
194 // Intrinsics that return a a predicate.
195 static unsigned doesIntrinsicReturnPredicate(unsigned ID)
196 {
197   switch (ID) {
198     default:
199       return 0;
200     case Intrinsic::hexagon_C2_cmpeq:
201     case Intrinsic::hexagon_C2_cmpgt:
202     case Intrinsic::hexagon_C2_cmpgtu:
203     case Intrinsic::hexagon_C2_cmpgtup:
204     case Intrinsic::hexagon_C2_cmpgtp:
205     case Intrinsic::hexagon_C2_cmpeqp:
206     case Intrinsic::hexagon_C2_bitsset:
207     case Intrinsic::hexagon_C2_bitsclr:
208     case Intrinsic::hexagon_C2_cmpeqi:
209     case Intrinsic::hexagon_C2_cmpgti:
210     case Intrinsic::hexagon_C2_cmpgtui:
211     case Intrinsic::hexagon_C2_cmpgei:
212     case Intrinsic::hexagon_C2_cmpgeui:
213     case Intrinsic::hexagon_C2_cmplt:
214     case Intrinsic::hexagon_C2_cmpltu:
215     case Intrinsic::hexagon_C2_bitsclri:
216     case Intrinsic::hexagon_C2_and:
217     case Intrinsic::hexagon_C2_or:
218     case Intrinsic::hexagon_C2_xor:
219     case Intrinsic::hexagon_C2_andn:
220     case Intrinsic::hexagon_C2_not:
221     case Intrinsic::hexagon_C2_orn:
222     case Intrinsic::hexagon_C2_pxfer_map:
223     case Intrinsic::hexagon_C2_any8:
224     case Intrinsic::hexagon_C2_all8:
225     case Intrinsic::hexagon_A2_vcmpbeq:
226     case Intrinsic::hexagon_A2_vcmpbgtu:
227     case Intrinsic::hexagon_A2_vcmpheq:
228     case Intrinsic::hexagon_A2_vcmphgt:
229     case Intrinsic::hexagon_A2_vcmphgtu:
230     case Intrinsic::hexagon_A2_vcmpweq:
231     case Intrinsic::hexagon_A2_vcmpwgt:
232     case Intrinsic::hexagon_A2_vcmpwgtu:
233     case Intrinsic::hexagon_C2_tfrrp:
234     case Intrinsic::hexagon_S2_tstbit_i:
235     case Intrinsic::hexagon_S2_tstbit_r:
236       return 1;
237   }
238 }
239
240 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadSignExtend64(LoadSDNode *LD,
241                                                            unsigned Opcode,
242                                                            SDLoc dl) {
243   SDValue Chain = LD->getChain();
244   EVT LoadedVT = LD->getMemoryVT();
245   SDValue Base = LD->getBasePtr();
246   SDValue Offset = LD->getOffset();
247   SDNode *OffsetNode = Offset.getNode();
248   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
249
250   const HexagonInstrInfo &TII = *HST.getInstrInfo();
251   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
252     SDValue TargetConst = CurDAG->getTargetConstant(Val, MVT::i32);
253     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::i32,
254                                               MVT::Other, Base, TargetConst,
255                                               Chain);
256     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
257                                               SDValue(Result_1, 0));
258     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
259     MemOp[0] = LD->getMemOperand();
260     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
261     const SDValue Froms[] = { SDValue(LD, 0),
262                               SDValue(LD, 1),
263                               SDValue(LD, 2) };
264     const SDValue Tos[]   = { SDValue(Result_2, 0),
265                               SDValue(Result_1, 1),
266                               SDValue(Result_1, 2) };
267     ReplaceUses(Froms, Tos, 3);
268     return Result_2;
269   }
270
271   SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
272   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
273   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
274                                             Base, TargetConst0, Chain);
275   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
276                                             SDValue(Result_1, 0));
277   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
278                                             Base, TargetConstVal,
279                                             SDValue(Result_1, 1));
280   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
281   MemOp[0] = LD->getMemOperand();
282   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
283   const SDValue Froms[] = { SDValue(LD, 0),
284                             SDValue(LD, 1),
285                             SDValue(LD, 2) };
286   const SDValue Tos[]   = { SDValue(Result_2, 0),
287                             SDValue(Result_3, 0),
288                             SDValue(Result_1, 1) };
289   ReplaceUses(Froms, Tos, 3);
290   return Result_2;
291 }
292
293
294 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadZeroExtend64(LoadSDNode *LD,
295                                                            unsigned Opcode,
296                                                            SDLoc dl) {
297   SDValue Chain = LD->getChain();
298   EVT LoadedVT = LD->getMemoryVT();
299   SDValue Base = LD->getBasePtr();
300   SDValue Offset = LD->getOffset();
301   SDNode *OffsetNode = Offset.getNode();
302   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
303
304   const HexagonInstrInfo &TII = *HST.getInstrInfo();
305   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
306     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
307     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
308     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
309                                               MVT::i32, MVT::Other, Base,
310                                               TargetConstVal, Chain);
311     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
312                                               MVT::i64, MVT::Other,
313                                               TargetConst0,
314                                               SDValue(Result_1,0));
315     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
316     MemOp[0] = LD->getMemOperand();
317     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
318     const SDValue Froms[] = { SDValue(LD, 0),
319                               SDValue(LD, 1),
320                               SDValue(LD, 2) };
321     const SDValue Tos[]   = { SDValue(Result_2, 0),
322                               SDValue(Result_1, 1),
323                               SDValue(Result_1, 2) };
324     ReplaceUses(Froms, Tos, 3);
325     return Result_2;
326   }
327
328   // Generate an indirect load.
329   SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
330   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
331   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
332                                             MVT::Other, Base, TargetConst0,
333                                             Chain);
334   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
335                                             MVT::i64, MVT::Other,
336                                             TargetConst0,
337                                             SDValue(Result_1,0));
338   // Add offset to base.
339   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
340                                             Base, TargetConstVal,
341                                             SDValue(Result_1, 1));
342   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
343   MemOp[0] = LD->getMemOperand();
344   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
345   const SDValue Froms[] = { SDValue(LD, 0),
346                             SDValue(LD, 1),
347                             SDValue(LD, 2) };
348   const SDValue Tos[]   = { SDValue(Result_2, 0), // Load value.
349                             SDValue(Result_3, 0), // New address.
350                             SDValue(Result_1, 1) };
351   ReplaceUses(Froms, Tos, 3);
352   return Result_2;
353 }
354
355
356 SDNode *HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, SDLoc dl) {
357   SDValue Chain = LD->getChain();
358   SDValue Base = LD->getBasePtr();
359   SDValue Offset = LD->getOffset();
360   SDNode *OffsetNode = Offset.getNode();
361   // Get the constant value.
362   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
363   EVT LoadedVT = LD->getMemoryVT();
364   unsigned Opcode = 0;
365
366   // Check for zero extended loads. Treat any-extend loads as zero extended
367   // loads.
368   ISD::LoadExtType ExtType = LD->getExtensionType();
369   bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
370
371   // Figure out the opcode.
372   const HexagonInstrInfo &TII = *HST.getInstrInfo();
373   if (LoadedVT == MVT::i64) {
374     if (TII.isValidAutoIncImm(LoadedVT, Val))
375       Opcode = Hexagon::L2_loadrd_pi;
376     else
377       Opcode = Hexagon::L2_loadrd_io;
378   } else if (LoadedVT == MVT::i32) {
379     if (TII.isValidAutoIncImm(LoadedVT, Val))
380       Opcode = Hexagon::L2_loadri_pi;
381     else
382       Opcode = Hexagon::L2_loadri_io;
383   } else if (LoadedVT == MVT::i16) {
384     if (TII.isValidAutoIncImm(LoadedVT, Val))
385       Opcode = IsZeroExt ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadrh_pi;
386     else
387       Opcode = IsZeroExt ? Hexagon::L2_loadruh_io : Hexagon::L2_loadrh_io;
388   } else if (LoadedVT == MVT::i8) {
389     if (TII.isValidAutoIncImm(LoadedVT, Val))
390       Opcode = IsZeroExt ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrb_pi;
391     else
392       Opcode = IsZeroExt ? Hexagon::L2_loadrub_io : Hexagon::L2_loadrb_io;
393   } else
394     llvm_unreachable("unknown memory type");
395
396   // For zero extended i64 loads, we need to add combine instructions.
397   if (LD->getValueType(0) == MVT::i64 && IsZeroExt)
398     return SelectIndexedLoadZeroExtend64(LD, Opcode, dl);
399   // Handle sign extended i64 loads.
400   if (LD->getValueType(0) == MVT::i64 && ExtType == ISD::SEXTLOAD)
401     return SelectIndexedLoadSignExtend64(LD, Opcode, dl);
402
403   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
404     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
405     SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
406                                             LD->getValueType(0),
407                                             MVT::i32, MVT::Other, Base,
408                                             TargetConstVal, Chain);
409     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
410     MemOp[0] = LD->getMemOperand();
411     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
412     const SDValue Froms[] = { SDValue(LD, 0),
413                               SDValue(LD, 1),
414                               SDValue(LD, 2)
415     };
416     const SDValue Tos[]   = { SDValue(Result, 0),
417                               SDValue(Result, 1),
418                               SDValue(Result, 2)
419     };
420     ReplaceUses(Froms, Tos, 3);
421     return Result;
422   } else {
423     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
424     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
425     SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl,
426                                               LD->getValueType(0),
427                                               MVT::Other, Base, TargetConst0,
428                                               Chain);
429     SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
430                                               Base, TargetConstVal,
431                                               SDValue(Result_1, 1));
432     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
433     MemOp[0] = LD->getMemOperand();
434     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
435     const SDValue Froms[] = { SDValue(LD, 0),
436                               SDValue(LD, 1),
437                               SDValue(LD, 2)
438     };
439     const SDValue Tos[]   = { SDValue(Result_1, 0),
440                               SDValue(Result_2, 0),
441                               SDValue(Result_1, 1)
442     };
443     ReplaceUses(Froms, Tos, 3);
444     return Result_1;
445   }
446 }
447
448
449 SDNode *HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
450   SDNode *result;
451   SDLoc dl(N);
452   LoadSDNode *LD = cast<LoadSDNode>(N);
453   ISD::MemIndexedMode AM = LD->getAddressingMode();
454
455   // Handle indexed loads.
456   if (AM != ISD::UNINDEXED) {
457     result = SelectIndexedLoad(LD, dl);
458   } else {
459     result = SelectCode(LD);
460   }
461
462   return result;
463 }
464
465
466 SDNode *HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, SDLoc dl) {
467   SDValue Chain = ST->getChain();
468   SDValue Base = ST->getBasePtr();
469   SDValue Offset = ST->getOffset();
470   SDValue Value = ST->getValue();
471   SDNode *OffsetNode = Offset.getNode();
472   // Get the constant value.
473   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
474   EVT StoredVT = ST->getMemoryVT();
475   EVT ValueVT = Value.getValueType();
476
477   // Offset value must be within representable range
478   // and must have correct alignment properties.
479   const HexagonInstrInfo &TII = *HST.getInstrInfo();
480   if (TII.isValidAutoIncImm(StoredVT, Val)) {
481     unsigned Opcode = 0;
482
483     // Figure out the post inc version of opcode.
484     if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_pi;
485     else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_pi;
486     else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_pi;
487     else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_pi;
488     else llvm_unreachable("unknown memory type");
489
490     if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
491       assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
492       Value = CurDAG->getTargetExtractSubreg(Hexagon::subreg_loreg,
493                                              dl, MVT::i32, Value);
494     }
495     SDValue Ops[] = {Base, CurDAG->getTargetConstant(Val, MVT::i32), Value,
496                      Chain};
497     // Build post increment store.
498     SDNode* Result = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
499                                             MVT::Other, Ops);
500     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
501     MemOp[0] = ST->getMemOperand();
502     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
503
504     ReplaceUses(ST, Result);
505     ReplaceUses(SDValue(ST,1), SDValue(Result,1));
506     return Result;
507   }
508
509   // Note: Order of operands matches the def of instruction:
510   // def S2_storerd_io
511   //   : STInst<(outs), (ins IntRegs:$base, imm:$offset, DoubleRegs:$src1), ...
512   // and it differs for POST_ST* for instance.
513   SDValue Ops[] = { Base, CurDAG->getTargetConstant(0, MVT::i32), Value,
514                     Chain};
515   unsigned Opcode = 0;
516
517   // Figure out the opcode.
518   if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_io;
519   else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_io;
520   else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_io;
521   else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_io;
522   else llvm_unreachable("unknown memory type");
523
524   // Build regular store.
525   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
526   SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
527   // Build splitted incriment instruction.
528   SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
529                                             Base,
530                                             TargetConstVal,
531                                             SDValue(Result_1, 0));
532   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
533   MemOp[0] = ST->getMemOperand();
534   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
535
536   ReplaceUses(SDValue(ST,0), SDValue(Result_2,0));
537   ReplaceUses(SDValue(ST,1), SDValue(Result_1,0));
538   return Result_2;
539 }
540
541 SDNode *HexagonDAGToDAGISel::SelectStore(SDNode *N) {
542   SDLoc dl(N);
543   StoreSDNode *ST = cast<StoreSDNode>(N);
544   ISD::MemIndexedMode AM = ST->getAddressingMode();
545
546   // Handle indexed stores.
547   if (AM != ISD::UNINDEXED) {
548     return SelectIndexedStore(ST, dl);
549   }
550
551   return SelectCode(ST);
552 }
553
554 SDNode *HexagonDAGToDAGISel::SelectMul(SDNode *N) {
555   SDLoc dl(N);
556
557   //
558   // %conv.i = sext i32 %tmp1 to i64
559   // %conv2.i = sext i32 %add to i64
560   // %mul.i = mul nsw i64 %conv2.i, %conv.i
561   //
562   //   --- match with the following ---
563   //
564   // %mul.i = mpy (%tmp1, %add)
565   //
566
567   if (N->getValueType(0) == MVT::i64) {
568     // Shifting a i64 signed multiply.
569     SDValue MulOp0 = N->getOperand(0);
570     SDValue MulOp1 = N->getOperand(1);
571
572     SDValue OP0;
573     SDValue OP1;
574
575     // Handle sign_extend and sextload.
576     if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
577       SDValue Sext0 = MulOp0.getOperand(0);
578       if (Sext0.getNode()->getValueType(0) != MVT::i32) {
579         return SelectCode(N);
580       }
581
582       OP0 = Sext0;
583     } else if (MulOp0.getOpcode() == ISD::LOAD) {
584       LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
585       if (LD->getMemoryVT() != MVT::i32 ||
586           LD->getExtensionType() != ISD::SEXTLOAD ||
587           LD->getAddressingMode() != ISD::UNINDEXED) {
588         return SelectCode(N);
589       }
590
591       SDValue Chain = LD->getChain();
592       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
593       OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
594                                             MVT::Other,
595                                             LD->getBasePtr(), TargetConst0,
596                                             Chain), 0);
597     } else {
598       return SelectCode(N);
599     }
600
601     // Same goes for the second operand.
602     if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
603       SDValue Sext1 = MulOp1.getOperand(0);
604       if (Sext1.getNode()->getValueType(0) != MVT::i32) {
605         return SelectCode(N);
606       }
607
608       OP1 = Sext1;
609     } else if (MulOp1.getOpcode() == ISD::LOAD) {
610       LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
611       if (LD->getMemoryVT() != MVT::i32 ||
612           LD->getExtensionType() != ISD::SEXTLOAD ||
613           LD->getAddressingMode() != ISD::UNINDEXED) {
614         return SelectCode(N);
615       }
616
617       SDValue Chain = LD->getChain();
618       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
619       OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
620                                             MVT::Other,
621                                             LD->getBasePtr(), TargetConst0,
622                                             Chain), 0);
623     } else {
624       return SelectCode(N);
625     }
626
627     // Generate a mpy instruction.
628     SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_dpmpyss_s0, dl, MVT::i64,
629                                             OP0, OP1);
630     ReplaceUses(N, Result);
631     return Result;
632   }
633
634   return SelectCode(N);
635 }
636
637
638 SDNode *HexagonDAGToDAGISel::SelectSelect(SDNode *N) {
639   SDLoc dl(N);
640   SDValue N0 = N->getOperand(0);
641   if (N0.getOpcode() == ISD::SETCC) {
642     SDValue N00 = N0.getOperand(0);
643     if (N00.getOpcode() == ISD::SIGN_EXTEND_INREG) {
644       SDValue N000 = N00.getOperand(0);
645       SDValue N001 = N00.getOperand(1);
646       if (cast<VTSDNode>(N001)->getVT() == MVT::i16) {
647         SDValue N01 = N0.getOperand(1);
648         SDValue N02 = N0.getOperand(2);
649
650         // Pattern: (select:i32 (setcc:i1 (sext_inreg:i32 IntRegs:i32:$src2,
651         // i16:Other),IntRegs:i32:$src1, SETLT:Other),IntRegs:i32:$src1,
652         // IntRegs:i32:$src2)
653         // Emits: (MAXh_rr:i32 IntRegs:i32:$src1, IntRegs:i32:$src2)
654         // Pattern complexity = 9  cost = 1  size = 0.
655         if (cast<CondCodeSDNode>(N02)->get() == ISD::SETLT) {
656           SDValue N1 = N->getOperand(1);
657           if (N01 == N1) {
658             SDValue N2 = N->getOperand(2);
659             if (N000 == N2 &&
660                 N0.getNode()->getValueType(N0.getResNo()) == MVT::i1 &&
661                 N00.getNode()->getValueType(N00.getResNo()) == MVT::i32) {
662               SDNode *SextNode = CurDAG->getMachineNode(Hexagon::A2_sxth, dl,
663                                                         MVT::i32, N000);
664               SDNode *Result = CurDAG->getMachineNode(Hexagon::A2_max, dl,
665                                                       MVT::i32,
666                                                       SDValue(SextNode, 0),
667                                                       N1);
668               ReplaceUses(N, Result);
669               return Result;
670             }
671           }
672         }
673
674         // Pattern: (select:i32 (setcc:i1 (sext_inreg:i32 IntRegs:i32:$src2,
675         // i16:Other), IntRegs:i32:$src1, SETGT:Other), IntRegs:i32:$src1,
676         // IntRegs:i32:$src2)
677         // Emits: (MINh_rr:i32 IntRegs:i32:$src1, IntRegs:i32:$src2)
678         // Pattern complexity = 9  cost = 1  size = 0.
679         if (cast<CondCodeSDNode>(N02)->get() == ISD::SETGT) {
680           SDValue N1 = N->getOperand(1);
681           if (N01 == N1) {
682             SDValue N2 = N->getOperand(2);
683             if (N000 == N2 &&
684                 N0.getNode()->getValueType(N0.getResNo()) == MVT::i1 &&
685                 N00.getNode()->getValueType(N00.getResNo()) == MVT::i32) {
686               SDNode *SextNode = CurDAG->getMachineNode(Hexagon::A2_sxth, dl,
687                                                         MVT::i32, N000);
688               SDNode *Result = CurDAG->getMachineNode(Hexagon::A2_min, dl,
689                                                       MVT::i32,
690                                                       SDValue(SextNode, 0),
691                                                       N1);
692               ReplaceUses(N, Result);
693               return Result;
694             }
695           }
696         }
697       }
698     }
699   }
700
701   return SelectCode(N);
702 }
703
704
705 SDNode *HexagonDAGToDAGISel::SelectTruncate(SDNode *N) {
706   SDLoc dl(N);
707   SDValue Shift = N->getOperand(0);
708
709   //
710   // %conv.i = sext i32 %tmp1 to i64
711   // %conv2.i = sext i32 %add to i64
712   // %mul.i = mul nsw i64 %conv2.i, %conv.i
713   // %shr5.i = lshr i64 %mul.i, 32
714   // %conv3.i = trunc i64 %shr5.i to i32
715   //
716   //   --- match with the following ---
717   //
718   // %conv3.i = mpy (%tmp1, %add)
719   //
720   // Trunc to i32.
721   if (N->getValueType(0) == MVT::i32) {
722     // Trunc from i64.
723     if (Shift.getNode()->getValueType(0) == MVT::i64) {
724       // Trunc child is logical shift right.
725       if (Shift.getOpcode() != ISD::SRL) {
726         return SelectCode(N);
727       }
728
729       SDValue ShiftOp0 = Shift.getOperand(0);
730       SDValue ShiftOp1 = Shift.getOperand(1);
731
732       // Shift by const 32
733       if (ShiftOp1.getOpcode() != ISD::Constant) {
734         return SelectCode(N);
735       }
736
737       int32_t ShiftConst =
738         cast<ConstantSDNode>(ShiftOp1.getNode())->getSExtValue();
739       if (ShiftConst != 32) {
740         return SelectCode(N);
741       }
742
743       // Shifting a i64 signed multiply
744       SDValue Mul = ShiftOp0;
745       if (Mul.getOpcode() != ISD::MUL) {
746         return SelectCode(N);
747       }
748
749       SDValue MulOp0 = Mul.getOperand(0);
750       SDValue MulOp1 = Mul.getOperand(1);
751
752       SDValue OP0;
753       SDValue OP1;
754
755       // Handle sign_extend and sextload
756       if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
757         SDValue Sext0 = MulOp0.getOperand(0);
758         if (Sext0.getNode()->getValueType(0) != MVT::i32) {
759           return SelectCode(N);
760         }
761
762         OP0 = Sext0;
763       } else if (MulOp0.getOpcode() == ISD::LOAD) {
764         LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
765         if (LD->getMemoryVT() != MVT::i32 ||
766             LD->getExtensionType() != ISD::SEXTLOAD ||
767             LD->getAddressingMode() != ISD::UNINDEXED) {
768           return SelectCode(N);
769         }
770
771         SDValue Chain = LD->getChain();
772         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
773         OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
774                                               MVT::Other,
775                                               LD->getBasePtr(),
776                                               TargetConst0, Chain), 0);
777       } else {
778         return SelectCode(N);
779       }
780
781       // Same goes for the second operand.
782       if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
783         SDValue Sext1 = MulOp1.getOperand(0);
784         if (Sext1.getNode()->getValueType(0) != MVT::i32)
785           return SelectCode(N);
786
787         OP1 = Sext1;
788       } else if (MulOp1.getOpcode() == ISD::LOAD) {
789         LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
790         if (LD->getMemoryVT() != MVT::i32 ||
791             LD->getExtensionType() != ISD::SEXTLOAD ||
792             LD->getAddressingMode() != ISD::UNINDEXED) {
793           return SelectCode(N);
794         }
795
796         SDValue Chain = LD->getChain();
797         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
798         OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
799                                               MVT::Other,
800                                               LD->getBasePtr(),
801                                               TargetConst0, Chain), 0);
802       } else {
803         return SelectCode(N);
804       }
805
806       // Generate a mpy instruction.
807       SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpy_up, dl, MVT::i32,
808                                               OP0, OP1);
809       ReplaceUses(N, Result);
810       return Result;
811     }
812   }
813
814   return SelectCode(N);
815 }
816
817
818 SDNode *HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
819   SDLoc dl(N);
820   if (N->getValueType(0) == MVT::i32) {
821     SDValue Shl_0 = N->getOperand(0);
822     SDValue Shl_1 = N->getOperand(1);
823     // RHS is const.
824     if (Shl_1.getOpcode() == ISD::Constant) {
825       if (Shl_0.getOpcode() == ISD::MUL) {
826         SDValue Mul_0 = Shl_0.getOperand(0); // Val
827         SDValue Mul_1 = Shl_0.getOperand(1); // Const
828         // RHS of mul is const.
829         if (Mul_1.getOpcode() == ISD::Constant) {
830           int32_t ShlConst =
831             cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
832           int32_t MulConst =
833             cast<ConstantSDNode>(Mul_1.getNode())->getSExtValue();
834           int32_t ValConst = MulConst << ShlConst;
835           SDValue Val = CurDAG->getTargetConstant(ValConst,
836                                                   MVT::i32);
837           if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val.getNode()))
838             if (isInt<9>(CN->getSExtValue())) {
839               SDNode* Result =
840                 CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
841                                        MVT::i32, Mul_0, Val);
842               ReplaceUses(N, Result);
843               return Result;
844             }
845
846         }
847       } else if (Shl_0.getOpcode() == ISD::SUB) {
848         SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
849         SDValue Sub_1 = Shl_0.getOperand(1); // Val
850         if (Sub_0.getOpcode() == ISD::Constant) {
851           int32_t SubConst =
852             cast<ConstantSDNode>(Sub_0.getNode())->getSExtValue();
853           if (SubConst == 0) {
854             if (Sub_1.getOpcode() == ISD::SHL) {
855               SDValue Shl2_0 = Sub_1.getOperand(0); // Val
856               SDValue Shl2_1 = Sub_1.getOperand(1); // Const
857               if (Shl2_1.getOpcode() == ISD::Constant) {
858                 int32_t ShlConst =
859                   cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
860                 int32_t Shl2Const =
861                   cast<ConstantSDNode>(Shl2_1.getNode())->getSExtValue();
862                 int32_t ValConst = 1 << (ShlConst+Shl2Const);
863                 SDValue Val = CurDAG->getTargetConstant(-ValConst, MVT::i32);
864                 if (ConstantSDNode *CN =
865                     dyn_cast<ConstantSDNode>(Val.getNode()))
866                   if (isInt<9>(CN->getSExtValue())) {
867                     SDNode* Result =
868                       CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl, MVT::i32,
869                                              Shl2_0, Val);
870                     ReplaceUses(N, Result);
871                     return Result;
872                   }
873               }
874             }
875           }
876         }
877       }
878     }
879   }
880   return SelectCode(N);
881 }
882
883
884 //
885 // If there is an zero_extend followed an intrinsic in DAG (this means - the
886 // result of the intrinsic is predicate); convert the zero_extend to
887 // transfer instruction.
888 //
889 // Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
890 // converted into a MUX as predicate registers defined as 1 bit in the
891 // compiler. Architecture defines them as 8-bit registers.
892 // We want to preserve all the lower 8-bits and, not just 1 LSB bit.
893 //
894 SDNode *HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
895   SDLoc dl(N);
896   SDNode *IsIntrinsic = N->getOperand(0).getNode();
897   if ((IsIntrinsic->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
898     unsigned ID =
899       cast<ConstantSDNode>(IsIntrinsic->getOperand(0))->getZExtValue();
900     if (doesIntrinsicReturnPredicate(ID)) {
901       // Now we need to differentiate target data types.
902       if (N->getValueType(0) == MVT::i64) {
903         // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
904         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
905         SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
906                                                   MVT::i32,
907                                                   SDValue(IsIntrinsic, 0));
908         SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
909                                                   MVT::i32,
910                                                   TargetConst0);
911         SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
912                                                   MVT::i64, MVT::Other,
913                                                   SDValue(Result_2, 0),
914                                                   SDValue(Result_1, 0));
915         ReplaceUses(N, Result_3);
916         return Result_3;
917       }
918       if (N->getValueType(0) == MVT::i32) {
919         // Convert the zero_extend to Rs = Pd
920         SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
921                                               MVT::i32,
922                                               SDValue(IsIntrinsic, 0));
923         ReplaceUses(N, RsPd);
924         return RsPd;
925       }
926       llvm_unreachable("Unexpected value type");
927     }
928   }
929   return SelectCode(N);
930 }
931
932 //
933 // Checking for intrinsics which have predicate registers as operand(s)
934 // and lowering to the actual intrinsic.
935 //
936 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
937   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
938   unsigned Bits;
939   switch (IID) {
940   case Intrinsic::hexagon_S2_vsplatrb:
941     Bits = 8;
942     break;
943   case Intrinsic::hexagon_S2_vsplatrh:
944     Bits = 16;
945     break;
946   default:
947     return SelectCode(N);
948   }
949
950   SDValue const &V = N->getOperand(1);
951   SDValue U;
952   if (isValueExtension(V, Bits, U)) {
953     SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
954       N->getOperand(0), U);
955     return SelectCode(R.getNode());
956   }
957   return SelectCode(N);
958 }
959
960 //
961 // Map floating point constant values.
962 //
963 SDNode *HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
964   SDLoc dl(N);
965   ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
966   APFloat APF = CN->getValueAPF();
967   if (N->getValueType(0) == MVT::f32) {
968     return CurDAG->getMachineNode(Hexagon::TFRI_f, dl, MVT::f32,
969               CurDAG->getTargetConstantFP(APF.convertToFloat(), MVT::f32));
970   }
971   else if (N->getValueType(0) == MVT::f64) {
972     return CurDAG->getMachineNode(Hexagon::CONST64_Float_Real, dl, MVT::f64,
973               CurDAG->getTargetConstantFP(APF.convertToDouble(), MVT::f64));
974   }
975
976   return SelectCode(N);
977 }
978
979 //
980 // Map predicate true (encoded as -1 in LLVM) to a XOR.
981 //
982 SDNode *HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
983   SDLoc dl(N);
984   if (N->getValueType(0) == MVT::i1) {
985     SDNode* Result;
986     int32_t Val = cast<ConstantSDNode>(N)->getSExtValue();
987     if (Val == -1) {
988       // Create the IntReg = 1 node.
989       SDNode* IntRegTFR =
990         CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32,
991                                CurDAG->getTargetConstant(0, MVT::i32));
992
993       // Pd = IntReg
994       SDNode* Pd = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::i1,
995                                           SDValue(IntRegTFR, 0));
996
997       // not(Pd)
998       SDNode* NotPd = CurDAG->getMachineNode(Hexagon::C2_not, dl, MVT::i1,
999                                              SDValue(Pd, 0));
1000
1001       // xor(not(Pd))
1002       Result = CurDAG->getMachineNode(Hexagon::C2_xor, dl, MVT::i1,
1003                                       SDValue(Pd, 0), SDValue(NotPd, 0));
1004
1005       // We have just built:
1006       // Rs = Pd
1007       // Pd = xor(not(Pd), Pd)
1008
1009       ReplaceUses(N, Result);
1010       return Result;
1011     }
1012   }
1013
1014   return SelectCode(N);
1015 }
1016
1017
1018 //
1019 // Map add followed by a asr -> asr +=.
1020 //
1021 SDNode *HexagonDAGToDAGISel::SelectAdd(SDNode *N) {
1022   SDLoc dl(N);
1023   if (N->getValueType(0) != MVT::i32) {
1024     return SelectCode(N);
1025   }
1026   // Identify nodes of the form: add(asr(...)).
1027   SDNode* Src1 = N->getOperand(0).getNode();
1028   if (Src1->getOpcode() != ISD::SRA || !Src1->hasOneUse()
1029       || Src1->getValueType(0) != MVT::i32) {
1030     return SelectCode(N);
1031   }
1032
1033   // Build Rd = Rd' + asr(Rs, Rt). The machine constraints will ensure that
1034   // Rd and Rd' are assigned to the same register
1035   SDNode* Result = CurDAG->getMachineNode(Hexagon::S2_asr_r_r_acc, dl, MVT::i32,
1036                                           N->getOperand(1),
1037                                           Src1->getOperand(0),
1038                                           Src1->getOperand(1));
1039   ReplaceUses(N, Result);
1040
1041   return Result;
1042 }
1043
1044 SDNode *HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
1045   int FX = cast<FrameIndexSDNode>(N)->getIndex();
1046   SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1047   SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
1048   SDLoc DL(N);
1049
1050   SDNode *R = CurDAG->getMachineNode(Hexagon::TFR_FI, DL, MVT::i32, FI, Zero);
1051
1052   if (N->getHasDebugValue())
1053     CurDAG->TransferDbgValues(SDValue(N, 0), SDValue(R, 0));
1054   return R;
1055 }
1056
1057
1058 SDNode *HexagonDAGToDAGISel::Select(SDNode *N) {
1059   if (N->isMachineOpcode()) {
1060     N->setNodeId(-1);
1061     return nullptr;   // Already selected.
1062   }
1063
1064   switch (N->getOpcode()) {
1065   case ISD::Constant:
1066     return SelectConstant(N);
1067
1068   case ISD::ConstantFP:
1069     return SelectConstantFP(N);
1070
1071   case ISD::FrameIndex:
1072     return SelectFrameIndex(N);
1073
1074   case ISD::ADD:
1075     return SelectAdd(N);
1076
1077   case ISD::SHL:
1078     return SelectSHL(N);
1079
1080   case ISD::LOAD:
1081     return SelectLoad(N);
1082
1083   case ISD::STORE:
1084     return SelectStore(N);
1085
1086   case ISD::SELECT:
1087     return SelectSelect(N);
1088
1089   case ISD::TRUNCATE:
1090     return SelectTruncate(N);
1091
1092   case ISD::MUL:
1093     return SelectMul(N);
1094
1095   case ISD::ZERO_EXTEND:
1096     return SelectZeroExtend(N);
1097
1098   case ISD::INTRINSIC_WO_CHAIN:
1099     return SelectIntrinsicWOChain(N);
1100   }
1101
1102   return SelectCode(N);
1103 }
1104
1105
1106 bool HexagonDAGToDAGISel::
1107 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
1108                              std::vector<SDValue> &OutOps) {
1109   SDValue Inp = Op, Res;
1110
1111   switch (ConstraintID) {
1112   default:
1113     return true;
1114   case InlineAsm::Constraint_i:
1115   case InlineAsm::Constraint_o: // Offsetable.
1116   case InlineAsm::Constraint_v: // Not offsetable.
1117   case InlineAsm::Constraint_m: // Memory.
1118     if (SelectAddrFI(Inp, Res))
1119       OutOps.push_back(Res);
1120     else
1121       OutOps.push_back(Inp);
1122     break;
1123   }
1124
1125   OutOps.push_back(CurDAG->getTargetConstant(0, MVT::i32));
1126   return false;
1127 }
1128
1129 void HexagonDAGToDAGISel::PreprocessISelDAG() {
1130   SelectionDAG &DAG = *CurDAG;
1131   std::vector<SDNode*> Nodes;
1132   for (auto I = DAG.allnodes_begin(), E = DAG.allnodes_end(); I != E; ++I)
1133     Nodes.push_back(I);
1134
1135   // Simplify: (or (select c x 0) z)  ->  (select c (or x z) z)
1136   //           (or (select c 0 y) z)  ->  (select c z (or y z))
1137   // This may not be the right thing for all targets, so do it here.
1138   for (auto I: Nodes) {
1139     if (I->getOpcode() != ISD::OR)
1140       continue;
1141
1142     auto IsZero = [] (const SDValue &V) -> bool {
1143       if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
1144         return SC->isNullValue();
1145       return false;
1146     };
1147     auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
1148       if (Op.getOpcode() != ISD::SELECT)
1149         return false;
1150       return IsZero(Op.getOperand(1))  || IsZero(Op.getOperand(2));
1151     };
1152
1153     SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
1154     EVT VT = I->getValueType(0);
1155     bool SelN0 = IsSelect0(N0);
1156     SDValue SOp = SelN0 ? N0 : N1;
1157     SDValue VOp = SelN0 ? N1 : N0;
1158
1159     if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
1160       SDValue SC = SOp.getOperand(0);
1161       SDValue SX = SOp.getOperand(1);
1162       SDValue SY = SOp.getOperand(2);
1163       SDLoc DLS = SOp;
1164       if (IsZero(SY)) {
1165         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
1166         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
1167         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1168       } else if (IsZero(SX)) {
1169         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1170         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1171         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1172       }
1173     }
1174   }
1175 }
1176
1177
1178 bool HexagonDAGToDAGISel::SelectAddrFI(SDValue& N, SDValue &R) {
1179   if (N.getOpcode() != ISD::FrameIndex)
1180     return false;
1181   FrameIndexSDNode *FX = cast<FrameIndexSDNode>(N);
1182   R = CurDAG->getTargetFrameIndex(FX->getIndex(), MVT::i32);
1183   return true;
1184 }
1185
1186 inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1187   return SelectGlobalAddress(N, R, false);
1188 }
1189
1190 inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1191   return SelectGlobalAddress(N, R, true);
1192 }
1193
1194 bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1195                                               bool UseGP) {
1196   switch (N.getOpcode()) {
1197   case ISD::ADD: {
1198     SDValue N0 = N.getOperand(0);
1199     SDValue N1 = N.getOperand(1);
1200     unsigned GAOpc = N0.getOpcode();
1201     if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1202       return false;
1203     if (!UseGP && GAOpc != HexagonISD::CONST32)
1204       return false;
1205     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1206       SDValue Addr = N0.getOperand(0);
1207       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1208         if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1209           uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1210           R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1211                                              N.getValueType(), NewOff);
1212           return true;
1213         }
1214       }
1215     }
1216     break;
1217   }
1218   case HexagonISD::CONST32:
1219     // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1220     // want in the instruction.
1221     if (!UseGP)
1222       R = N.getOperand(0);
1223     return !UseGP;
1224   case HexagonISD::CONST32_GP:
1225     if (UseGP)
1226       R = N.getOperand(0);
1227     return UseGP;
1228   default:
1229     return false;
1230   }
1231
1232   return false;
1233 }
1234
1235 bool HexagonDAGToDAGISel::isValueExtension(const SDValue &Val,
1236       unsigned FromBits, SDValue &Src) {
1237   unsigned Opc = Val.getOpcode();
1238   switch (Opc) {
1239   case ISD::SIGN_EXTEND:
1240   case ISD::ZERO_EXTEND:
1241   case ISD::ANY_EXTEND: {
1242     SDValue const &Op0 = Val.getOperand(0);
1243     EVT T = Op0.getValueType();
1244     if (T.isInteger() && T.getSizeInBits() == FromBits) {
1245       Src = Op0;
1246       return true;
1247     }
1248     break;
1249   }
1250   case ISD::SIGN_EXTEND_INREG:
1251   case ISD::AssertSext:
1252   case ISD::AssertZext:
1253     if (Val.getOperand(0).getValueType().isInteger()) {
1254       VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1255       if (T->getVT().getSizeInBits() == FromBits) {
1256         Src = Val.getOperand(0);
1257         return true;
1258       }
1259     }
1260     break;
1261   case ISD::AND: {
1262     // Check if this is an AND with "FromBits" of lower bits set to 1.
1263     uint64_t FromMask = (1 << FromBits) - 1;
1264     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1265       if (C->getZExtValue() == FromMask) {
1266         Src = Val.getOperand(1);
1267         return true;
1268       }
1269     }
1270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1271       if (C->getZExtValue() == FromMask) {
1272         Src = Val.getOperand(0);
1273         return true;
1274       }
1275     }
1276     break;
1277   }
1278   case ISD::OR:
1279   case ISD::XOR: {
1280     // OR/XOR with the lower "FromBits" bits set to 0.
1281     uint64_t FromMask = (1 << FromBits) - 1;
1282     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1283       if ((C->getZExtValue() & FromMask) == 0) {
1284         Src = Val.getOperand(1);
1285         return true;
1286       }
1287     }
1288     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1289       if ((C->getZExtValue() & FromMask) == 0) {
1290         Src = Val.getOperand(0);
1291         return true;
1292       }
1293     }
1294   }
1295   default:
1296     break;
1297   }
1298   return false;
1299 }