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