[Hexagon] Use pseudo-instructions for true/false predicate values
[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 *SelectMul(SDNode *N);
89   SDNode *SelectZeroExtend(SDNode *N);
90   SDNode *SelectIntrinsicWChain(SDNode *N);
91   SDNode *SelectIntrinsicWOChain(SDNode *N);
92   SDNode *SelectConstant(SDNode *N);
93   SDNode *SelectConstantFP(SDNode *N);
94   SDNode *SelectAdd(SDNode *N);
95   SDNode *SelectBitOp(SDNode *N);
96
97   // XformMskToBitPosU5Imm - Returns the bit position which
98   // the single bit 32 bit mask represents.
99   // Used in Clr and Set bit immediate memops.
100   SDValue XformMskToBitPosU5Imm(uint32_t Imm) {
101     int32_t bitPos;
102     bitPos = Log2_32(Imm);
103     assert(bitPos >= 0 && bitPos < 32 &&
104            "Constant out of range for 32 BitPos Memops");
105     return CurDAG->getTargetConstant(bitPos, MVT::i32);
106   }
107
108   // XformMskToBitPosU4Imm - Returns the bit position which the single-bit
109   // 16 bit mask represents. Used in Clr and Set bit immediate memops.
110   SDValue XformMskToBitPosU4Imm(uint16_t Imm) {
111     return XformMskToBitPosU5Imm(Imm);
112   }
113
114   // XformMskToBitPosU3Imm - Returns the bit position which the single-bit
115   // 8 bit mask represents. Used in Clr and Set bit immediate memops.
116   SDValue XformMskToBitPosU3Imm(uint8_t Imm) {
117     return XformMskToBitPosU5Imm(Imm);
118   }
119
120   // Return true if there is exactly one bit set in V, i.e., if V is one of the
121   // following integers: 2^0, 2^1, ..., 2^31.
122   bool ImmIsSingleBit(uint32_t v) const {
123     return isPowerOf2_32(v);
124   }
125
126   // XformM5ToU5Imm - Return a target constant with the specified value, of
127   // type i32 where the negative literal is transformed into a positive literal
128   // for use in -= memops.
129   inline SDValue XformM5ToU5Imm(signed Imm) {
130      assert( (Imm >= -31 && Imm <= -1)  && "Constant out of range for Memops");
131      return CurDAG->getTargetConstant( - Imm, MVT::i32);
132   }
133
134   // XformU7ToU7M1Imm - Return a target constant decremented by 1, in range
135   // [1..128], used in cmpb.gtu instructions.
136   inline SDValue XformU7ToU7M1Imm(signed Imm) {
137     assert((Imm >= 1 && Imm <= 128) && "Constant out of range for cmpb op");
138     return CurDAG->getTargetConstant(Imm - 1, MVT::i8);
139   }
140
141   // XformS8ToS8M1Imm - Return a target constant decremented by 1.
142   inline SDValue XformSToSM1Imm(signed Imm) {
143     return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
144   }
145
146   // XformU8ToU8M1Imm - Return a target constant decremented by 1.
147   inline SDValue XformUToUM1Imm(unsigned Imm) {
148     assert((Imm >= 1) && "Cannot decrement unsigned int less than 1");
149     return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
150   }
151
152   // XformSToSM2Imm - Return a target constant decremented by 2.
153   inline SDValue XformSToSM2Imm(unsigned Imm) {
154     return CurDAG->getTargetConstant(Imm - 2, MVT::i32);
155   }
156
157   // XformSToSM3Imm - Return a target constant decremented by 3.
158   inline SDValue XformSToSM3Imm(unsigned Imm) {
159     return CurDAG->getTargetConstant(Imm - 3, MVT::i32);
160   }
161
162   // Include the pieces autogenerated from the target description.
163   #include "HexagonGenDAGISel.inc"
164
165 private:
166   bool isValueExtension(const SDValue &Val, unsigned FromBits, SDValue &Src);
167 }; // end HexagonDAGToDAGISel
168 }  // end anonymous namespace
169
170
171 /// createHexagonISelDag - This pass converts a legalized DAG into a
172 /// Hexagon-specific DAG, ready for instruction scheduling.
173 ///
174 namespace llvm {
175 FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
176                                    CodeGenOpt::Level OptLevel) {
177   return new HexagonDAGToDAGISel(TM, OptLevel);
178 }
179 }
180
181 static void initializePassOnce(PassRegistry &Registry) {
182   const char *Name = "Hexagon DAG->DAG Pattern Instruction Selection";
183   PassInfo *PI = new PassInfo(Name, "hexagon-isel",
184                               &SelectionDAGISel::ID, nullptr, false, false);
185   Registry.registerPass(*PI, true);
186 }
187
188 void llvm::initializeHexagonDAGToDAGISelPass(PassRegistry &Registry) {
189   CALL_ONCE_INITIALIZATION(initializePassOnce)
190 }
191
192
193 // Intrinsics that return a a predicate.
194 static unsigned doesIntrinsicReturnPredicate(unsigned ID)
195 {
196   switch (ID) {
197     default:
198       return 0;
199     case Intrinsic::hexagon_C2_cmpeq:
200     case Intrinsic::hexagon_C2_cmpgt:
201     case Intrinsic::hexagon_C2_cmpgtu:
202     case Intrinsic::hexagon_C2_cmpgtup:
203     case Intrinsic::hexagon_C2_cmpgtp:
204     case Intrinsic::hexagon_C2_cmpeqp:
205     case Intrinsic::hexagon_C2_bitsset:
206     case Intrinsic::hexagon_C2_bitsclr:
207     case Intrinsic::hexagon_C2_cmpeqi:
208     case Intrinsic::hexagon_C2_cmpgti:
209     case Intrinsic::hexagon_C2_cmpgtui:
210     case Intrinsic::hexagon_C2_cmpgei:
211     case Intrinsic::hexagon_C2_cmpgeui:
212     case Intrinsic::hexagon_C2_cmplt:
213     case Intrinsic::hexagon_C2_cmpltu:
214     case Intrinsic::hexagon_C2_bitsclri:
215     case Intrinsic::hexagon_C2_and:
216     case Intrinsic::hexagon_C2_or:
217     case Intrinsic::hexagon_C2_xor:
218     case Intrinsic::hexagon_C2_andn:
219     case Intrinsic::hexagon_C2_not:
220     case Intrinsic::hexagon_C2_orn:
221     case Intrinsic::hexagon_C2_pxfer_map:
222     case Intrinsic::hexagon_C2_any8:
223     case Intrinsic::hexagon_C2_all8:
224     case Intrinsic::hexagon_A2_vcmpbeq:
225     case Intrinsic::hexagon_A2_vcmpbgtu:
226     case Intrinsic::hexagon_A2_vcmpheq:
227     case Intrinsic::hexagon_A2_vcmphgt:
228     case Intrinsic::hexagon_A2_vcmphgtu:
229     case Intrinsic::hexagon_A2_vcmpweq:
230     case Intrinsic::hexagon_A2_vcmpwgt:
231     case Intrinsic::hexagon_A2_vcmpwgtu:
232     case Intrinsic::hexagon_C2_tfrrp:
233     case Intrinsic::hexagon_S2_tstbit_i:
234     case Intrinsic::hexagon_S2_tstbit_r:
235       return 1;
236   }
237 }
238
239 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadSignExtend64(LoadSDNode *LD,
240                                                            unsigned Opcode,
241                                                            SDLoc dl) {
242   SDValue Chain = LD->getChain();
243   EVT LoadedVT = LD->getMemoryVT();
244   SDValue Base = LD->getBasePtr();
245   SDValue Offset = LD->getOffset();
246   SDNode *OffsetNode = Offset.getNode();
247   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
248
249   const HexagonInstrInfo &TII = *HST.getInstrInfo();
250   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
251     SDValue TargetConst = CurDAG->getTargetConstant(Val, MVT::i32);
252     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::i32,
253                                               MVT::Other, Base, TargetConst,
254                                               Chain);
255     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
256                                               SDValue(Result_1, 0));
257     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
258     MemOp[0] = LD->getMemOperand();
259     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
260     const SDValue Froms[] = { SDValue(LD, 0),
261                               SDValue(LD, 1),
262                               SDValue(LD, 2) };
263     const SDValue Tos[]   = { SDValue(Result_2, 0),
264                               SDValue(Result_1, 1),
265                               SDValue(Result_1, 2) };
266     ReplaceUses(Froms, Tos, 3);
267     return Result_2;
268   }
269
270   SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
271   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
272   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
273                                             Base, TargetConst0, Chain);
274   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
275                                             SDValue(Result_1, 0));
276   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
277                                             Base, TargetConstVal,
278                                             SDValue(Result_1, 1));
279   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
280   MemOp[0] = LD->getMemOperand();
281   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
282   const SDValue Froms[] = { SDValue(LD, 0),
283                             SDValue(LD, 1),
284                             SDValue(LD, 2) };
285   const SDValue Tos[]   = { SDValue(Result_2, 0),
286                             SDValue(Result_3, 0),
287                             SDValue(Result_1, 1) };
288   ReplaceUses(Froms, Tos, 3);
289   return Result_2;
290 }
291
292
293 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadZeroExtend64(LoadSDNode *LD,
294                                                            unsigned Opcode,
295                                                            SDLoc dl) {
296   SDValue Chain = LD->getChain();
297   EVT LoadedVT = LD->getMemoryVT();
298   SDValue Base = LD->getBasePtr();
299   SDValue Offset = LD->getOffset();
300   SDNode *OffsetNode = Offset.getNode();
301   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
302
303   const HexagonInstrInfo &TII = *HST.getInstrInfo();
304   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
305     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
306     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
307     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
308                                               MVT::i32, MVT::Other, Base,
309                                               TargetConstVal, Chain);
310     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
311                                               MVT::i64, MVT::Other,
312                                               TargetConst0,
313                                               SDValue(Result_1,0));
314     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
315     MemOp[0] = LD->getMemOperand();
316     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
317     const SDValue Froms[] = { SDValue(LD, 0),
318                               SDValue(LD, 1),
319                               SDValue(LD, 2) };
320     const SDValue Tos[]   = { SDValue(Result_2, 0),
321                               SDValue(Result_1, 1),
322                               SDValue(Result_1, 2) };
323     ReplaceUses(Froms, Tos, 3);
324     return Result_2;
325   }
326
327   // Generate an indirect load.
328   SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
329   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
330   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
331                                             MVT::Other, Base, TargetConst0,
332                                             Chain);
333   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
334                                             MVT::i64, MVT::Other,
335                                             TargetConst0,
336                                             SDValue(Result_1,0));
337   // Add offset to base.
338   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
339                                             Base, TargetConstVal,
340                                             SDValue(Result_1, 1));
341   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
342   MemOp[0] = LD->getMemOperand();
343   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
344   const SDValue Froms[] = { SDValue(LD, 0),
345                             SDValue(LD, 1),
346                             SDValue(LD, 2) };
347   const SDValue Tos[]   = { SDValue(Result_2, 0), // Load value.
348                             SDValue(Result_3, 0), // New address.
349                             SDValue(Result_1, 1) };
350   ReplaceUses(Froms, Tos, 3);
351   return Result_2;
352 }
353
354
355 SDNode *HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, SDLoc dl) {
356   SDValue Chain = LD->getChain();
357   SDValue Base = LD->getBasePtr();
358   SDValue Offset = LD->getOffset();
359   SDNode *OffsetNode = Offset.getNode();
360   // Get the constant value.
361   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
362   EVT LoadedVT = LD->getMemoryVT();
363   unsigned Opcode = 0;
364
365   // Check for zero extended loads. Treat any-extend loads as zero extended
366   // loads.
367   ISD::LoadExtType ExtType = LD->getExtensionType();
368   bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
369
370   // Figure out the opcode.
371   const HexagonInstrInfo &TII = *HST.getInstrInfo();
372   if (LoadedVT == MVT::i64) {
373     if (TII.isValidAutoIncImm(LoadedVT, Val))
374       Opcode = Hexagon::L2_loadrd_pi;
375     else
376       Opcode = Hexagon::L2_loadrd_io;
377   } else if (LoadedVT == MVT::i32) {
378     if (TII.isValidAutoIncImm(LoadedVT, Val))
379       Opcode = Hexagon::L2_loadri_pi;
380     else
381       Opcode = Hexagon::L2_loadri_io;
382   } else if (LoadedVT == MVT::i16) {
383     if (TII.isValidAutoIncImm(LoadedVT, Val))
384       Opcode = IsZeroExt ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadrh_pi;
385     else
386       Opcode = IsZeroExt ? Hexagon::L2_loadruh_io : Hexagon::L2_loadrh_io;
387   } else if (LoadedVT == MVT::i8) {
388     if (TII.isValidAutoIncImm(LoadedVT, Val))
389       Opcode = IsZeroExt ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrb_pi;
390     else
391       Opcode = IsZeroExt ? Hexagon::L2_loadrub_io : Hexagon::L2_loadrb_io;
392   } else
393     llvm_unreachable("unknown memory type");
394
395   // For zero extended i64 loads, we need to add combine instructions.
396   if (LD->getValueType(0) == MVT::i64 && IsZeroExt)
397     return SelectIndexedLoadZeroExtend64(LD, Opcode, dl);
398   // Handle sign extended i64 loads.
399   if (LD->getValueType(0) == MVT::i64 && ExtType == ISD::SEXTLOAD)
400     return SelectIndexedLoadSignExtend64(LD, Opcode, dl);
401
402   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
403     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
404     SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
405                                             LD->getValueType(0),
406                                             MVT::i32, MVT::Other, Base,
407                                             TargetConstVal, Chain);
408     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
409     MemOp[0] = LD->getMemOperand();
410     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
411     const SDValue Froms[] = { SDValue(LD, 0),
412                               SDValue(LD, 1),
413                               SDValue(LD, 2)
414     };
415     const SDValue Tos[]   = { SDValue(Result, 0),
416                               SDValue(Result, 1),
417                               SDValue(Result, 2)
418     };
419     ReplaceUses(Froms, Tos, 3);
420     return Result;
421   } else {
422     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
423     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
424     SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl,
425                                               LD->getValueType(0),
426                                               MVT::Other, Base, TargetConst0,
427                                               Chain);
428     SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
429                                               Base, TargetConstVal,
430                                               SDValue(Result_1, 1));
431     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
432     MemOp[0] = LD->getMemOperand();
433     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
434     const SDValue Froms[] = { SDValue(LD, 0),
435                               SDValue(LD, 1),
436                               SDValue(LD, 2)
437     };
438     const SDValue Tos[]   = { SDValue(Result_1, 0),
439                               SDValue(Result_2, 0),
440                               SDValue(Result_1, 1)
441     };
442     ReplaceUses(Froms, Tos, 3);
443     return Result_1;
444   }
445 }
446
447
448 SDNode *HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
449   SDNode *result;
450   SDLoc dl(N);
451   LoadSDNode *LD = cast<LoadSDNode>(N);
452   ISD::MemIndexedMode AM = LD->getAddressingMode();
453
454   // Handle indexed loads.
455   if (AM != ISD::UNINDEXED) {
456     result = SelectIndexedLoad(LD, dl);
457   } else {
458     result = SelectCode(LD);
459   }
460
461   return result;
462 }
463
464
465 SDNode *HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, SDLoc dl) {
466   SDValue Chain = ST->getChain();
467   SDValue Base = ST->getBasePtr();
468   SDValue Offset = ST->getOffset();
469   SDValue Value = ST->getValue();
470   SDNode *OffsetNode = Offset.getNode();
471   // Get the constant value.
472   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
473   EVT StoredVT = ST->getMemoryVT();
474   EVT ValueVT = Value.getValueType();
475
476   // Offset value must be within representable range
477   // and must have correct alignment properties.
478   const HexagonInstrInfo &TII = *HST.getInstrInfo();
479   if (TII.isValidAutoIncImm(StoredVT, Val)) {
480     unsigned Opcode = 0;
481
482     // Figure out the post inc version of opcode.
483     if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_pi;
484     else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_pi;
485     else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_pi;
486     else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_pi;
487     else llvm_unreachable("unknown memory type");
488
489     if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
490       assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
491       Value = CurDAG->getTargetExtractSubreg(Hexagon::subreg_loreg,
492                                              dl, MVT::i32, Value);
493     }
494     SDValue Ops[] = {Base, CurDAG->getTargetConstant(Val, MVT::i32), Value,
495                      Chain};
496     // Build post increment store.
497     SDNode* Result = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
498                                             MVT::Other, Ops);
499     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
500     MemOp[0] = ST->getMemOperand();
501     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
502
503     ReplaceUses(ST, Result);
504     ReplaceUses(SDValue(ST,1), SDValue(Result,1));
505     return Result;
506   }
507
508   // Note: Order of operands matches the def of instruction:
509   // def S2_storerd_io
510   //   : STInst<(outs), (ins IntRegs:$base, imm:$offset, DoubleRegs:$src1), ...
511   // and it differs for POST_ST* for instance.
512   SDValue Ops[] = { Base, CurDAG->getTargetConstant(0, MVT::i32), Value,
513                     Chain};
514   unsigned Opcode = 0;
515
516   // Figure out the opcode.
517   if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_io;
518   else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_io;
519   else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_io;
520   else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_io;
521   else llvm_unreachable("unknown memory type");
522
523   // Build regular store.
524   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
525   SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
526   // Build splitted incriment instruction.
527   SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
528                                             Base,
529                                             TargetConstVal,
530                                             SDValue(Result_1, 0));
531   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
532   MemOp[0] = ST->getMemOperand();
533   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
534
535   ReplaceUses(SDValue(ST,0), SDValue(Result_2,0));
536   ReplaceUses(SDValue(ST,1), SDValue(Result_1,0));
537   return Result_2;
538 }
539
540 SDNode *HexagonDAGToDAGISel::SelectStore(SDNode *N) {
541   SDLoc dl(N);
542   StoreSDNode *ST = cast<StoreSDNode>(N);
543   ISD::MemIndexedMode AM = ST->getAddressingMode();
544
545   // Handle indexed stores.
546   if (AM != ISD::UNINDEXED) {
547     return SelectIndexedStore(ST, dl);
548   }
549
550   return SelectCode(ST);
551 }
552
553 SDNode *HexagonDAGToDAGISel::SelectMul(SDNode *N) {
554   SDLoc dl(N);
555
556   //
557   // %conv.i = sext i32 %tmp1 to i64
558   // %conv2.i = sext i32 %add to i64
559   // %mul.i = mul nsw i64 %conv2.i, %conv.i
560   //
561   //   --- match with the following ---
562   //
563   // %mul.i = mpy (%tmp1, %add)
564   //
565
566   if (N->getValueType(0) == MVT::i64) {
567     // Shifting a i64 signed multiply.
568     SDValue MulOp0 = N->getOperand(0);
569     SDValue MulOp1 = N->getOperand(1);
570
571     SDValue OP0;
572     SDValue OP1;
573
574     // Handle sign_extend and sextload.
575     if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
576       SDValue Sext0 = MulOp0.getOperand(0);
577       if (Sext0.getNode()->getValueType(0) != MVT::i32) {
578         return SelectCode(N);
579       }
580
581       OP0 = Sext0;
582     } else if (MulOp0.getOpcode() == ISD::LOAD) {
583       LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
584       if (LD->getMemoryVT() != MVT::i32 ||
585           LD->getExtensionType() != ISD::SEXTLOAD ||
586           LD->getAddressingMode() != ISD::UNINDEXED) {
587         return SelectCode(N);
588       }
589
590       SDValue Chain = LD->getChain();
591       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
592       OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
593                                             MVT::Other,
594                                             LD->getBasePtr(), TargetConst0,
595                                             Chain), 0);
596     } else {
597       return SelectCode(N);
598     }
599
600     // Same goes for the second operand.
601     if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
602       SDValue Sext1 = MulOp1.getOperand(0);
603       if (Sext1.getNode()->getValueType(0) != MVT::i32) {
604         return SelectCode(N);
605       }
606
607       OP1 = Sext1;
608     } else if (MulOp1.getOpcode() == ISD::LOAD) {
609       LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
610       if (LD->getMemoryVT() != MVT::i32 ||
611           LD->getExtensionType() != ISD::SEXTLOAD ||
612           LD->getAddressingMode() != ISD::UNINDEXED) {
613         return SelectCode(N);
614       }
615
616       SDValue Chain = LD->getChain();
617       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
618       OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
619                                             MVT::Other,
620                                             LD->getBasePtr(), TargetConst0,
621                                             Chain), 0);
622     } else {
623       return SelectCode(N);
624     }
625
626     // Generate a mpy instruction.
627     SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_dpmpyss_s0, dl, MVT::i64,
628                                             OP0, OP1);
629     ReplaceUses(N, Result);
630     return Result;
631   }
632
633   return SelectCode(N);
634 }
635
636 SDNode *HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
637   SDLoc dl(N);
638   if (N->getValueType(0) == MVT::i32) {
639     SDValue Shl_0 = N->getOperand(0);
640     SDValue Shl_1 = N->getOperand(1);
641     // RHS is const.
642     if (Shl_1.getOpcode() == ISD::Constant) {
643       if (Shl_0.getOpcode() == ISD::MUL) {
644         SDValue Mul_0 = Shl_0.getOperand(0); // Val
645         SDValue Mul_1 = Shl_0.getOperand(1); // Const
646         // RHS of mul is const.
647         if (Mul_1.getOpcode() == ISD::Constant) {
648           int32_t ShlConst =
649             cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
650           int32_t MulConst =
651             cast<ConstantSDNode>(Mul_1.getNode())->getSExtValue();
652           int32_t ValConst = MulConst << ShlConst;
653           SDValue Val = CurDAG->getTargetConstant(ValConst,
654                                                   MVT::i32);
655           if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val.getNode()))
656             if (isInt<9>(CN->getSExtValue())) {
657               SDNode* Result =
658                 CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
659                                        MVT::i32, Mul_0, Val);
660               ReplaceUses(N, Result);
661               return Result;
662             }
663
664         }
665       } else if (Shl_0.getOpcode() == ISD::SUB) {
666         SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
667         SDValue Sub_1 = Shl_0.getOperand(1); // Val
668         if (Sub_0.getOpcode() == ISD::Constant) {
669           int32_t SubConst =
670             cast<ConstantSDNode>(Sub_0.getNode())->getSExtValue();
671           if (SubConst == 0) {
672             if (Sub_1.getOpcode() == ISD::SHL) {
673               SDValue Shl2_0 = Sub_1.getOperand(0); // Val
674               SDValue Shl2_1 = Sub_1.getOperand(1); // Const
675               if (Shl2_1.getOpcode() == ISD::Constant) {
676                 int32_t ShlConst =
677                   cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
678                 int32_t Shl2Const =
679                   cast<ConstantSDNode>(Shl2_1.getNode())->getSExtValue();
680                 int32_t ValConst = 1 << (ShlConst+Shl2Const);
681                 SDValue Val = CurDAG->getTargetConstant(-ValConst, MVT::i32);
682                 if (ConstantSDNode *CN =
683                     dyn_cast<ConstantSDNode>(Val.getNode()))
684                   if (isInt<9>(CN->getSExtValue())) {
685                     SDNode* Result =
686                       CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl, MVT::i32,
687                                              Shl2_0, Val);
688                     ReplaceUses(N, Result);
689                     return Result;
690                   }
691               }
692             }
693           }
694         }
695       }
696     }
697   }
698   return SelectCode(N);
699 }
700
701
702 //
703 // If there is an zero_extend followed an intrinsic in DAG (this means - the
704 // result of the intrinsic is predicate); convert the zero_extend to
705 // transfer instruction.
706 //
707 // Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
708 // converted into a MUX as predicate registers defined as 1 bit in the
709 // compiler. Architecture defines them as 8-bit registers.
710 // We want to preserve all the lower 8-bits and, not just 1 LSB bit.
711 //
712 SDNode *HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
713   SDLoc dl(N);
714   SDNode *IsIntrinsic = N->getOperand(0).getNode();
715   if ((IsIntrinsic->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
716     unsigned ID =
717       cast<ConstantSDNode>(IsIntrinsic->getOperand(0))->getZExtValue();
718     if (doesIntrinsicReturnPredicate(ID)) {
719       // Now we need to differentiate target data types.
720       if (N->getValueType(0) == MVT::i64) {
721         // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
722         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
723         SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
724                                                   MVT::i32,
725                                                   SDValue(IsIntrinsic, 0));
726         SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
727                                                   MVT::i32,
728                                                   TargetConst0);
729         SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
730                                                   MVT::i64, MVT::Other,
731                                                   SDValue(Result_2, 0),
732                                                   SDValue(Result_1, 0));
733         ReplaceUses(N, Result_3);
734         return Result_3;
735       }
736       if (N->getValueType(0) == MVT::i32) {
737         // Convert the zero_extend to Rs = Pd
738         SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
739                                               MVT::i32,
740                                               SDValue(IsIntrinsic, 0));
741         ReplaceUses(N, RsPd);
742         return RsPd;
743       }
744       llvm_unreachable("Unexpected value type");
745     }
746   }
747   return SelectCode(N);
748 }
749
750 //
751 // Checking for intrinsics circular load/store, and bitreverse load/store
752 // instrisics in order to select the correct lowered operation.
753 //
754 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
755   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
756   if (IntNo == Intrinsic::hexagon_circ_ldd  ||
757       IntNo == Intrinsic::hexagon_circ_ldw  ||
758       IntNo == Intrinsic::hexagon_circ_lduh ||
759       IntNo == Intrinsic::hexagon_circ_ldh  ||
760       IntNo == Intrinsic::hexagon_circ_ldub ||
761       IntNo == Intrinsic::hexagon_circ_ldb) {
762     SDLoc dl(N);
763     SDValue Chain = N->getOperand(0);
764     SDValue Base = N->getOperand(2);
765     SDValue Load = N->getOperand(3);
766     SDValue ModifierExpr = N->getOperand(4);
767     SDValue Offset = N->getOperand(5);
768
769     // We need to add the rerurn type for the load.  This intrinsic has
770     // two return types, one for the load and one for the post-increment.
771     // Only the *_ld instructions push the extra return type, and bump the
772     // result node operand number correspondingly.
773     std::vector<EVT> ResTys;
774     unsigned opc;
775     unsigned memsize, align;
776     MVT MvtSize = MVT::i32;
777
778     if (IntNo == Intrinsic::hexagon_circ_ldd) {
779       ResTys.push_back(MVT::i32);
780       ResTys.push_back(MVT::i64);
781       opc = Hexagon::L2_loadrd_pci_pseudo;
782       memsize = 8;
783       align = 8;
784     } else if (IntNo == Intrinsic::hexagon_circ_ldw) {
785       ResTys.push_back(MVT::i32);
786       ResTys.push_back(MVT::i32);
787       opc = Hexagon::L2_loadri_pci_pseudo;
788       memsize = 4;
789       align = 4;
790     } else if (IntNo == Intrinsic::hexagon_circ_ldh) {
791       ResTys.push_back(MVT::i32);
792       ResTys.push_back(MVT::i32);
793       opc = Hexagon::L2_loadrh_pci_pseudo;
794       memsize = 2;
795       align = 2;
796       MvtSize = MVT::i16;
797     } else if (IntNo == Intrinsic::hexagon_circ_lduh) {
798       ResTys.push_back(MVT::i32);
799       ResTys.push_back(MVT::i32);
800       opc = Hexagon::L2_loadruh_pci_pseudo;
801       memsize = 2;
802       align = 2;
803       MvtSize = MVT::i16;
804     } else if (IntNo == Intrinsic::hexagon_circ_ldb) {
805       ResTys.push_back(MVT::i32);
806       ResTys.push_back(MVT::i32);
807       opc = Hexagon::L2_loadrb_pci_pseudo;
808       memsize = 1;
809       align = 1;
810       MvtSize = MVT::i8;
811     } else if (IntNo == Intrinsic::hexagon_circ_ldub) {
812       ResTys.push_back(MVT::i32);
813       ResTys.push_back(MVT::i32);
814       opc = Hexagon::L2_loadrub_pci_pseudo;
815       memsize = 1;
816       align = 1;
817       MvtSize = MVT::i8;
818     } else
819       llvm_unreachable("no opc");
820
821     ResTys.push_back(MVT::Other);
822
823     // Copy over the arguments, which are the same mostly.
824     SmallVector<SDValue, 5> Ops;
825     Ops.push_back(Base);
826     Ops.push_back(Load);
827     Ops.push_back(ModifierExpr);
828     int32_t Val = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
829     Ops.push_back(CurDAG->getTargetConstant(Val, MVT::i32));
830     Ops.push_back(Chain);
831     SDNode* Result = CurDAG->getMachineNode(opc, dl, ResTys, Ops);
832
833     SDValue ST;
834     MachineMemOperand *Mem =
835       MF->getMachineMemOperand(MachinePointerInfo(),
836                                MachineMemOperand::MOStore, memsize, align);
837     if (MvtSize != MVT::i32)
838       ST = CurDAG->getTruncStore(Chain, dl, SDValue(Result, 1), Load,
839                                  MvtSize, Mem);
840     else
841       ST = CurDAG->getStore(Chain, dl, SDValue(Result, 1), Load, Mem);
842
843     SDNode* Store = SelectStore(ST.getNode());
844
845     const SDValue Froms[] = { SDValue(N, 0),
846                               SDValue(N, 1) };
847     const SDValue Tos[]   = { SDValue(Result, 0),
848                               SDValue(Store, 0) };
849     ReplaceUses(Froms, Tos, 2);
850     return Result;
851   }
852
853   if (IntNo == Intrinsic::hexagon_brev_ldd  ||
854       IntNo == Intrinsic::hexagon_brev_ldw  ||
855       IntNo == Intrinsic::hexagon_brev_ldh  ||
856       IntNo == Intrinsic::hexagon_brev_lduh ||
857       IntNo == Intrinsic::hexagon_brev_ldb  ||
858       IntNo == Intrinsic::hexagon_brev_ldub) {
859     SDLoc dl(N);
860     SDValue Chain = N->getOperand(0);
861     SDValue Base = N->getOperand(2);
862     SDValue Load = N->getOperand(3);
863     SDValue ModifierExpr = N->getOperand(4);
864
865     // We need to add the rerurn type for the load.  This intrinsic has
866     // two return types, one for the load and one for the post-increment.
867     std::vector<EVT> ResTys;
868     unsigned opc;
869     unsigned memsize, align;
870     MVT MvtSize = MVT::i32;
871
872     if (IntNo == Intrinsic::hexagon_brev_ldd) {
873       ResTys.push_back(MVT::i32);
874       ResTys.push_back(MVT::i64);
875       opc = Hexagon::L2_loadrd_pbr_pseudo;
876       memsize = 8;
877       align = 8;
878     } else if (IntNo == Intrinsic::hexagon_brev_ldw) {
879       ResTys.push_back(MVT::i32);
880       ResTys.push_back(MVT::i32);
881       opc = Hexagon::L2_loadri_pbr_pseudo;
882       memsize = 4;
883       align = 4;
884     } else if (IntNo == Intrinsic::hexagon_brev_ldh) {
885       ResTys.push_back(MVT::i32);
886       ResTys.push_back(MVT::i32);
887       opc = Hexagon::L2_loadrh_pbr_pseudo;
888       memsize = 2;
889       align = 2;
890       MvtSize = MVT::i16;
891     } else if (IntNo == Intrinsic::hexagon_brev_lduh) {
892       ResTys.push_back(MVT::i32);
893       ResTys.push_back(MVT::i32);
894       opc = Hexagon::L2_loadruh_pbr_pseudo;
895       memsize = 2;
896       align = 2;
897       MvtSize = MVT::i16;
898     } else if (IntNo == Intrinsic::hexagon_brev_ldb) {
899       ResTys.push_back(MVT::i32);
900       ResTys.push_back(MVT::i32);
901       opc = Hexagon::L2_loadrb_pbr_pseudo;
902       memsize = 1;
903       align = 1;
904       MvtSize = MVT::i8;
905     } else if (IntNo == Intrinsic::hexagon_brev_ldub) {
906       ResTys.push_back(MVT::i32);
907       ResTys.push_back(MVT::i32);
908       opc = Hexagon::L2_loadrub_pbr_pseudo;
909       memsize = 1;
910       align = 1;
911       MvtSize = MVT::i8;
912     } else
913       llvm_unreachable("no opc");
914
915     ResTys.push_back(MVT::Other);
916
917     // Copy over the arguments, which are the same mostly.
918     SmallVector<SDValue, 4> Ops;
919     Ops.push_back(Base);
920     Ops.push_back(Load);
921     Ops.push_back(ModifierExpr);
922     Ops.push_back(Chain);
923     SDNode* Result = CurDAG->getMachineNode(opc, dl, ResTys, Ops);
924     SDValue ST;
925     MachineMemOperand *Mem =
926       MF->getMachineMemOperand(MachinePointerInfo(),
927                                MachineMemOperand::MOStore, memsize, align);
928     if (MvtSize != MVT::i32)
929       ST = CurDAG->getTruncStore(Chain, dl, SDValue(Result, 1), Load,
930                                  MvtSize, Mem);
931     else
932       ST = CurDAG->getStore(Chain, dl, SDValue(Result, 1), Load, Mem);
933
934     SDNode* Store = SelectStore(ST.getNode());
935
936     const SDValue Froms[] = { SDValue(N, 0),
937                               SDValue(N, 1) };
938     const SDValue Tos[]   = { SDValue(Result, 0),
939                               SDValue(Store, 0) };
940     ReplaceUses(Froms, Tos, 2);
941     return Result;
942   }
943
944   return SelectCode(N);
945 }
946
947 //
948 // Checking for intrinsics which have predicate registers as operand(s)
949 // and lowering to the actual intrinsic.
950 //
951 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
952   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
953   unsigned Bits;
954   switch (IID) {
955   case Intrinsic::hexagon_S2_vsplatrb:
956     Bits = 8;
957     break;
958   case Intrinsic::hexagon_S2_vsplatrh:
959     Bits = 16;
960     break;
961   default:
962     return SelectCode(N);
963   }
964
965   SDValue const &V = N->getOperand(1);
966   SDValue U;
967   if (isValueExtension(V, Bits, U)) {
968     SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
969       N->getOperand(0), U);
970     return SelectCode(R.getNode());
971   }
972   return SelectCode(N);
973 }
974
975 //
976 // Map floating point constant values.
977 //
978 SDNode *HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
979   SDLoc dl(N);
980   ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
981   APFloat APF = CN->getValueAPF();
982   if (N->getValueType(0) == MVT::f32) {
983     return CurDAG->getMachineNode(Hexagon::TFRI_f, dl, MVT::f32,
984               CurDAG->getTargetConstantFP(APF.convertToFloat(), MVT::f32));
985   }
986   else if (N->getValueType(0) == MVT::f64) {
987     return CurDAG->getMachineNode(Hexagon::CONST64_Float_Real, dl, MVT::f64,
988               CurDAG->getTargetConstantFP(APF.convertToDouble(), MVT::f64));
989   }
990
991   return SelectCode(N);
992 }
993
994 //
995 // Map predicate true (encoded as -1 in LLVM) to a XOR.
996 //
997 SDNode *HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
998   SDLoc dl(N);
999   if (N->getValueType(0) == MVT::i1) {
1000     SDNode* Result = 0;
1001     int32_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1002     if (Val == -1) {
1003       Result = CurDAG->getMachineNode(Hexagon::TFR_PdTrue, dl, MVT::i1);
1004     } else if (Val == 0) {
1005       Result = CurDAG->getMachineNode(Hexagon::TFR_PdFalse, dl, MVT::i1);
1006     }
1007     if (Result) {
1008       ReplaceUses(N, Result);
1009       return Result;
1010     }
1011   }
1012
1013   return SelectCode(N);
1014 }
1015
1016
1017 //
1018 // Map add followed by a asr -> asr +=.
1019 //
1020 SDNode *HexagonDAGToDAGISel::SelectAdd(SDNode *N) {
1021   SDLoc dl(N);
1022   if (N->getValueType(0) != MVT::i32) {
1023     return SelectCode(N);
1024   }
1025   // Identify nodes of the form: add(asr(...)).
1026   SDNode* Src1 = N->getOperand(0).getNode();
1027   if (Src1->getOpcode() != ISD::SRA || !Src1->hasOneUse()
1028       || Src1->getValueType(0) != MVT::i32) {
1029     return SelectCode(N);
1030   }
1031
1032   // Build Rd = Rd' + asr(Rs, Rt). The machine constraints will ensure that
1033   // Rd and Rd' are assigned to the same register
1034   SDNode* Result = CurDAG->getMachineNode(Hexagon::S2_asr_r_r_acc, dl, MVT::i32,
1035                                           N->getOperand(1),
1036                                           Src1->getOperand(0),
1037                                           Src1->getOperand(1));
1038   ReplaceUses(N, Result);
1039
1040   return Result;
1041 }
1042
1043 //
1044 // Map the following, where possible.
1045 // AND/FABS -> clrbit
1046 // OR -> setbit
1047 // XOR/FNEG ->toggle_bit.
1048 //
1049 SDNode *HexagonDAGToDAGISel::SelectBitOp(SDNode *N) {
1050   SDLoc dl(N);
1051   EVT ValueVT = N->getValueType(0);
1052
1053   // We handle only 32 and 64-bit bit ops.
1054   if (!(ValueVT == MVT::i32 || ValueVT == MVT::i64 ||
1055         ValueVT == MVT::f32 || ValueVT == MVT::f64))
1056     return SelectCode(N);
1057
1058   // We handly only fabs and fneg for V5.
1059   unsigned Opc = N->getOpcode();
1060   if ((Opc == ISD::FABS || Opc == ISD::FNEG) && !HST.hasV5TOps())
1061     return SelectCode(N);
1062
1063   int64_t Val = 0;
1064   if (Opc != ISD::FABS && Opc != ISD::FNEG) {
1065     if (N->getOperand(1).getOpcode() == ISD::Constant)
1066       Val = cast<ConstantSDNode>((N)->getOperand(1))->getSExtValue();
1067     else
1068      return SelectCode(N);
1069   }
1070
1071   if (Opc == ISD::AND) {
1072     if (((ValueVT == MVT::i32) &&
1073                   (!((Val & 0x80000000) || (Val & 0x7fffffff)))) ||
1074         ((ValueVT == MVT::i64) &&
1075                   (!((Val & 0x8000000000000000) || (Val & 0x7fffffff)))))
1076       // If it's simple AND, do the normal op.
1077       return SelectCode(N);
1078     else
1079       Val = ~Val;
1080   }
1081
1082   // If OR or AND is being fed by shl, srl and, sra don't do this change,
1083   // because Hexagon provide |= &= on shl, srl, and sra.
1084   // Traverse the DAG to see if there is shl, srl and sra.
1085   if (Opc == ISD::OR || Opc == ISD::AND) {
1086     switch (N->getOperand(0)->getOpcode()) {
1087       default: break;
1088       case ISD::SRA:
1089       case ISD::SRL:
1090       case ISD::SHL:
1091         return SelectCode(N);
1092     }
1093   }
1094
1095   // Make sure it's power of 2.
1096   unsigned bitpos = 0;
1097   if (Opc != ISD::FABS && Opc != ISD::FNEG) {
1098     if (((ValueVT == MVT::i32) && !isPowerOf2_32(Val)) ||
1099         ((ValueVT == MVT::i64) && !isPowerOf2_64(Val)))
1100       return SelectCode(N);
1101
1102     // Get the bit position.
1103     while (!(Val & 1)) {
1104       Val >>= 1;
1105       ++bitpos;
1106     }
1107   } else {
1108     // For fabs and fneg, it's always the 31st bit.
1109     bitpos = 31;
1110   }
1111
1112   unsigned BitOpc = 0;
1113   // Set the right opcode for bitwise operations.
1114   switch(Opc) {
1115     default: llvm_unreachable("Only bit-wise/abs/neg operations are allowed.");
1116     case ISD::AND:
1117     case ISD::FABS:
1118       BitOpc = Hexagon::S2_clrbit_i;
1119       break;
1120     case ISD::OR:
1121       BitOpc = Hexagon::S2_setbit_i;
1122       break;
1123     case ISD::XOR:
1124     case ISD::FNEG:
1125       BitOpc = Hexagon::S2_togglebit_i;
1126       break;
1127   }
1128
1129   SDNode *Result;
1130   // Get the right SDVal for the opcode.
1131   SDValue SDVal = CurDAG->getTargetConstant(bitpos, MVT::i32);
1132
1133   if (ValueVT == MVT::i32 || ValueVT == MVT::f32) {
1134     Result = CurDAG->getMachineNode(BitOpc, dl, ValueVT,
1135                                     N->getOperand(0), SDVal);
1136   } else {
1137     // 64-bit gymnastic to use REG_SEQUENCE. But it's worth it.
1138     EVT SubValueVT;
1139     if (ValueVT == MVT::i64)
1140       SubValueVT = MVT::i32;
1141     else
1142       SubValueVT = MVT::f32;
1143
1144     SDNode *Reg = N->getOperand(0).getNode();
1145     SDValue RegClass = CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID,
1146                                                  MVT::i64);
1147
1148     SDValue SubregHiIdx = CurDAG->getTargetConstant(Hexagon::subreg_hireg,
1149                                                     MVT::i32);
1150     SDValue SubregLoIdx = CurDAG->getTargetConstant(Hexagon::subreg_loreg,
1151                                                     MVT::i32);
1152
1153     SDValue SubregHI = CurDAG->getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
1154                                                     MVT::i32, SDValue(Reg, 0));
1155
1156     SDValue SubregLO = CurDAG->getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
1157                                                     MVT::i32, SDValue(Reg, 0));
1158
1159     // Clear/set/toggle hi or lo registers depending on the bit position.
1160     if (SubValueVT != MVT::f32 && bitpos < 32) {
1161       SDNode *Result0 = CurDAG->getMachineNode(BitOpc, dl, SubValueVT,
1162                                                SubregLO, SDVal);
1163       const SDValue Ops[] = { RegClass, SubregHI, SubregHiIdx,
1164                               SDValue(Result0, 0), SubregLoIdx };
1165       Result = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1166                                       dl, ValueVT, Ops);
1167     } else {
1168       if (Opc != ISD::FABS && Opc != ISD::FNEG)
1169         SDVal = CurDAG->getTargetConstant(bitpos-32, MVT::i32);
1170       SDNode *Result0 = CurDAG->getMachineNode(BitOpc, dl, SubValueVT,
1171                                                SubregHI, SDVal);
1172       const SDValue Ops[] = { RegClass, SDValue(Result0, 0), SubregHiIdx,
1173                               SubregLO, SubregLoIdx };
1174       Result = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1175                                       dl, ValueVT, Ops);
1176     }
1177   }
1178
1179   ReplaceUses(N, Result);
1180   return Result;
1181 }
1182
1183
1184 SDNode *HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
1185   int FX = cast<FrameIndexSDNode>(N)->getIndex();
1186   SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1187   SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
1188   SDLoc DL(N);
1189
1190   SDNode *R = CurDAG->getMachineNode(Hexagon::TFR_FI, DL, MVT::i32, FI, Zero);
1191
1192   if (N->getHasDebugValue())
1193     CurDAG->TransferDbgValues(SDValue(N, 0), SDValue(R, 0));
1194   return R;
1195 }
1196
1197
1198 SDNode *HexagonDAGToDAGISel::Select(SDNode *N) {
1199   if (N->isMachineOpcode()) {
1200     N->setNodeId(-1);
1201     return nullptr;   // Already selected.
1202   }
1203
1204   switch (N->getOpcode()) {
1205   case ISD::Constant:
1206     return SelectConstant(N);
1207
1208   case ISD::ConstantFP:
1209     return SelectConstantFP(N);
1210
1211   case ISD::FrameIndex:
1212     return SelectFrameIndex(N);
1213
1214   case ISD::ADD:
1215     return SelectAdd(N);
1216
1217   case ISD::SHL:
1218     return SelectSHL(N);
1219
1220   case ISD::LOAD:
1221     return SelectLoad(N);
1222
1223   case ISD::STORE:
1224     return SelectStore(N);
1225
1226   case ISD::MUL:
1227     return SelectMul(N);
1228
1229   case ISD::AND:
1230   case ISD::OR:
1231   case ISD::XOR:
1232   case ISD::FABS:
1233   case ISD::FNEG:
1234     return SelectBitOp(N);
1235
1236   case ISD::ZERO_EXTEND:
1237     return SelectZeroExtend(N);
1238
1239   case ISD::INTRINSIC_W_CHAIN:
1240     return SelectIntrinsicWChain(N);
1241
1242   case ISD::INTRINSIC_WO_CHAIN:
1243     return SelectIntrinsicWOChain(N);
1244   }
1245
1246   return SelectCode(N);
1247 }
1248
1249
1250 bool HexagonDAGToDAGISel::
1251 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
1252                              std::vector<SDValue> &OutOps) {
1253   SDValue Inp = Op, Res;
1254
1255   switch (ConstraintID) {
1256   default:
1257     return true;
1258   case InlineAsm::Constraint_i:
1259   case InlineAsm::Constraint_o: // Offsetable.
1260   case InlineAsm::Constraint_v: // Not offsetable.
1261   case InlineAsm::Constraint_m: // Memory.
1262     if (SelectAddrFI(Inp, Res))
1263       OutOps.push_back(Res);
1264     else
1265       OutOps.push_back(Inp);
1266     break;
1267   }
1268
1269   OutOps.push_back(CurDAG->getTargetConstant(0, MVT::i32));
1270   return false;
1271 }
1272
1273 void HexagonDAGToDAGISel::PreprocessISelDAG() {
1274   SelectionDAG &DAG = *CurDAG;
1275   std::vector<SDNode*> Nodes;
1276   for (auto I = DAG.allnodes_begin(), E = DAG.allnodes_end(); I != E; ++I)
1277     Nodes.push_back(I);
1278
1279   // Simplify: (or (select c x 0) z)  ->  (select c (or x z) z)
1280   //           (or (select c 0 y) z)  ->  (select c z (or y z))
1281   // This may not be the right thing for all targets, so do it here.
1282   for (auto I: Nodes) {
1283     if (I->getOpcode() != ISD::OR)
1284       continue;
1285
1286     auto IsZero = [] (const SDValue &V) -> bool {
1287       if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
1288         return SC->isNullValue();
1289       return false;
1290     };
1291     auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
1292       if (Op.getOpcode() != ISD::SELECT)
1293         return false;
1294       return IsZero(Op.getOperand(1))  || IsZero(Op.getOperand(2));
1295     };
1296
1297     SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
1298     EVT VT = I->getValueType(0);
1299     bool SelN0 = IsSelect0(N0);
1300     SDValue SOp = SelN0 ? N0 : N1;
1301     SDValue VOp = SelN0 ? N1 : N0;
1302
1303     if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
1304       SDValue SC = SOp.getOperand(0);
1305       SDValue SX = SOp.getOperand(1);
1306       SDValue SY = SOp.getOperand(2);
1307       SDLoc DLS = SOp;
1308       if (IsZero(SY)) {
1309         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
1310         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
1311         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1312       } else if (IsZero(SX)) {
1313         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1314         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1315         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1316       }
1317     }
1318   }
1319 }
1320
1321
1322 bool HexagonDAGToDAGISel::SelectAddrFI(SDValue& N, SDValue &R) {
1323   if (N.getOpcode() != ISD::FrameIndex)
1324     return false;
1325   FrameIndexSDNode *FX = cast<FrameIndexSDNode>(N);
1326   R = CurDAG->getTargetFrameIndex(FX->getIndex(), MVT::i32);
1327   return true;
1328 }
1329
1330 inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1331   return SelectGlobalAddress(N, R, false);
1332 }
1333
1334 inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1335   return SelectGlobalAddress(N, R, true);
1336 }
1337
1338 bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1339                                               bool UseGP) {
1340   switch (N.getOpcode()) {
1341   case ISD::ADD: {
1342     SDValue N0 = N.getOperand(0);
1343     SDValue N1 = N.getOperand(1);
1344     unsigned GAOpc = N0.getOpcode();
1345     if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1346       return false;
1347     if (!UseGP && GAOpc != HexagonISD::CONST32)
1348       return false;
1349     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1350       SDValue Addr = N0.getOperand(0);
1351       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1352         if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1353           uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1354           R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1355                                              N.getValueType(), NewOff);
1356           return true;
1357         }
1358       }
1359     }
1360     break;
1361   }
1362   case HexagonISD::CONST32:
1363     // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1364     // want in the instruction.
1365     if (!UseGP)
1366       R = N.getOperand(0);
1367     return !UseGP;
1368   case HexagonISD::CONST32_GP:
1369     if (UseGP)
1370       R = N.getOperand(0);
1371     return UseGP;
1372   default:
1373     return false;
1374   }
1375
1376   return false;
1377 }
1378
1379 bool HexagonDAGToDAGISel::isValueExtension(const SDValue &Val,
1380       unsigned FromBits, SDValue &Src) {
1381   unsigned Opc = Val.getOpcode();
1382   switch (Opc) {
1383   case ISD::SIGN_EXTEND:
1384   case ISD::ZERO_EXTEND:
1385   case ISD::ANY_EXTEND: {
1386     SDValue const &Op0 = Val.getOperand(0);
1387     EVT T = Op0.getValueType();
1388     if (T.isInteger() && T.getSizeInBits() == FromBits) {
1389       Src = Op0;
1390       return true;
1391     }
1392     break;
1393   }
1394   case ISD::SIGN_EXTEND_INREG:
1395   case ISD::AssertSext:
1396   case ISD::AssertZext:
1397     if (Val.getOperand(0).getValueType().isInteger()) {
1398       VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1399       if (T->getVT().getSizeInBits() == FromBits) {
1400         Src = Val.getOperand(0);
1401         return true;
1402       }
1403     }
1404     break;
1405   case ISD::AND: {
1406     // Check if this is an AND with "FromBits" of lower bits set to 1.
1407     uint64_t FromMask = (1 << FromBits) - 1;
1408     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1409       if (C->getZExtValue() == FromMask) {
1410         Src = Val.getOperand(1);
1411         return true;
1412       }
1413     }
1414     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1415       if (C->getZExtValue() == FromMask) {
1416         Src = Val.getOperand(0);
1417         return true;
1418       }
1419     }
1420     break;
1421   }
1422   case ISD::OR:
1423   case ISD::XOR: {
1424     // OR/XOR with the lower "FromBits" bits set to 0.
1425     uint64_t FromMask = (1 << FromBits) - 1;
1426     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1427       if ((C->getZExtValue() & FromMask) == 0) {
1428         Src = Val.getOperand(1);
1429         return true;
1430       }
1431     }
1432     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1433       if ((C->getZExtValue() & FromMask) == 0) {
1434         Src = Val.getOperand(0);
1435         return true;
1436       }
1437     }
1438   }
1439   default:
1440     break;
1441   }
1442   return false;
1443 }