LLVM  10.0.0svn
LegalizeDAG.cpp
Go to the documentation of this file.
1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SelectionDAG::Legalize method.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/Debug.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstdint>
50 #include <tuple>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "legalizedag"
56 
57 namespace {
58 
59 /// Keeps track of state when getting the sign of a floating-point value as an
60 /// integer.
61 struct FloatSignAsInt {
62  EVT FloatVT;
63  SDValue Chain;
64  SDValue FloatPtr;
65  SDValue IntPtr;
66  MachinePointerInfo IntPointerInfo;
67  MachinePointerInfo FloatPointerInfo;
68  SDValue IntValue;
69  APInt SignMask;
70  uint8_t SignBit;
71 };
72 
73 //===----------------------------------------------------------------------===//
74 /// This takes an arbitrary SelectionDAG as input and
75 /// hacks on it until the target machine can handle it. This involves
76 /// eliminating value sizes the machine cannot handle (promoting small sizes to
77 /// large sizes or splitting up large values into small values) as well as
78 /// eliminating operations the machine cannot handle.
79 ///
80 /// This code also does a small amount of optimization and recognition of idioms
81 /// as part of its processing. For example, if a target does not support a
82 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
83 /// will attempt merge setcc and brc instructions into brcc's.
84 class SelectionDAGLegalize {
85  const TargetMachine &TM;
86  const TargetLowering &TLI;
87  SelectionDAG &DAG;
88 
89  /// The set of nodes which have already been legalized. We hold a
90  /// reference to it in order to update as necessary on node deletion.
91  SmallPtrSetImpl<SDNode *> &LegalizedNodes;
92 
93  /// A set of all the nodes updated during legalization.
94  SmallSetVector<SDNode *, 16> *UpdatedNodes;
95 
96  EVT getSetCCResultType(EVT VT) const {
97  return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
98  }
99 
100  // Libcall insertion helpers.
101 
102 public:
103  SelectionDAGLegalize(SelectionDAG &DAG,
104  SmallPtrSetImpl<SDNode *> &LegalizedNodes,
105  SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
106  : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
107  LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
108 
109  /// Legalizes the given operation.
110  void LegalizeOp(SDNode *Node);
111 
112 private:
113  SDValue OptimizeFloatStore(StoreSDNode *ST);
114 
115  void LegalizeLoadOps(SDNode *Node);
116  void LegalizeStoreOps(SDNode *Node);
117 
118  /// Some targets cannot handle a variable
119  /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
120  /// is necessary to spill the vector being inserted into to memory, perform
121  /// the insert there, and then read the result back.
122  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
123  const SDLoc &dl);
124  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
125  const SDLoc &dl);
126 
127  /// Return a vector shuffle operation which
128  /// performs the same shuffe in terms of order or result bytes, but on a type
129  /// whose vector element type is narrower than the original shuffle type.
130  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
131  SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
132  SDValue N1, SDValue N2,
133  ArrayRef<int> Mask) const;
134 
135  bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
136  bool &NeedInvert, const SDLoc &dl);
137 
138  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
139 
140  std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
141  SDNode *Node, bool isSigned);
142  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
143  RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
144  RTLIB::Libcall Call_F128,
145  RTLIB::Libcall Call_PPCF128);
146  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
147  RTLIB::Libcall Call_I8,
148  RTLIB::Libcall Call_I16,
149  RTLIB::Libcall Call_I32,
150  RTLIB::Libcall Call_I64,
151  RTLIB::Libcall Call_I128);
152  SDValue ExpandArgFPLibCall(SDNode *Node,
153  RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
154  RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
155  RTLIB::Libcall Call_PPCF128);
156  void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
157  void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
158 
159  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
160  const SDLoc &dl);
161  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
162  const SDLoc &dl, SDValue ChainIn);
163  SDValue ExpandBUILD_VECTOR(SDNode *Node);
164  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
165  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
166  SmallVectorImpl<SDValue> &Results);
167  void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
168  SDValue Value) const;
169  SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
170  SDValue NewIntValue) const;
171  SDValue ExpandFCOPYSIGN(SDNode *Node) const;
172  SDValue ExpandFABS(SDNode *Node) const;
173  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, EVT DestVT,
174  const SDLoc &dl);
175  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
176  const SDLoc &dl);
177  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
178  const SDLoc &dl);
179 
180  SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl);
181  SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl);
182 
183  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
184  SDValue ExpandInsertToVectorThroughStack(SDValue Op);
185  SDValue ExpandVectorBuildThroughStack(SDNode* Node);
186 
187  SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
188  SDValue ExpandConstant(ConstantSDNode *CP);
189 
190  // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
191  bool ExpandNode(SDNode *Node);
192  void ConvertNodeToLibcall(SDNode *Node);
193  void PromoteNode(SDNode *Node);
194 
195 public:
196  // Node replacement helpers
197 
198  void ReplacedNode(SDNode *N) {
199  LegalizedNodes.erase(N);
200  if (UpdatedNodes)
201  UpdatedNodes->insert(N);
202  }
203 
204  void ReplaceNode(SDNode *Old, SDNode *New) {
205  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
206  dbgs() << " with: "; New->dump(&DAG));
207 
208  assert(Old->getNumValues() == New->getNumValues() &&
209  "Replacing one node with another that produces a different number "
210  "of values!");
211  DAG.ReplaceAllUsesWith(Old, New);
212  if (UpdatedNodes)
213  UpdatedNodes->insert(New);
214  ReplacedNode(Old);
215  }
216 
217  void ReplaceNode(SDValue Old, SDValue New) {
218  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
219  dbgs() << " with: "; New->dump(&DAG));
220 
221  DAG.ReplaceAllUsesWith(Old, New);
222  if (UpdatedNodes)
223  UpdatedNodes->insert(New.getNode());
224  ReplacedNode(Old.getNode());
225  }
226 
227  void ReplaceNode(SDNode *Old, const SDValue *New) {
228  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
229 
230  DAG.ReplaceAllUsesWith(Old, New);
231  for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
232  LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
233  New[i]->dump(&DAG));
234  if (UpdatedNodes)
235  UpdatedNodes->insert(New[i].getNode());
236  }
237  ReplacedNode(Old);
238  }
239 };
240 
241 } // end anonymous namespace
242 
243 /// Return a vector shuffle operation which
244 /// performs the same shuffle in terms of order or result bytes, but on a type
245 /// whose vector element type is narrower than the original shuffle type.
246 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
247 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
248  EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
249  ArrayRef<int> Mask) const {
250  unsigned NumMaskElts = VT.getVectorNumElements();
251  unsigned NumDestElts = NVT.getVectorNumElements();
252  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
253 
254  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
255 
256  if (NumEltsGrowth == 1)
257  return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
258 
259  SmallVector<int, 8> NewMask;
260  for (unsigned i = 0; i != NumMaskElts; ++i) {
261  int Idx = Mask[i];
262  for (unsigned j = 0; j != NumEltsGrowth; ++j) {
263  if (Idx < 0)
264  NewMask.push_back(-1);
265  else
266  NewMask.push_back(Idx * NumEltsGrowth + j);
267  }
268  }
269  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
270  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
271  return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
272 }
273 
274 /// Expands the ConstantFP node to an integer constant or
275 /// a load from the constant pool.
276 SDValue
277 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
278  bool Extend = false;
279  SDLoc dl(CFP);
280 
281  // If a FP immediate is precise when represented as a float and if the
282  // target can do an extending load from float to double, we put it into
283  // the constant pool as a float, even if it's is statically typed as a
284  // double. This shrinks FP constants and canonicalizes them for targets where
285  // an FP extending load is the same cost as a normal load (such as on the x87
286  // fp stack or PPC FP unit).
287  EVT VT = CFP->getValueType(0);
288  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
289  if (!UseCP) {
290  assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
291  return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
292  (VT == MVT::f64) ? MVT::i64 : MVT::i32);
293  }
294 
295  APFloat APF = CFP->getValueAPF();
296  EVT OrigVT = VT;
297  EVT SVT = VT;
298 
299  // We don't want to shrink SNaNs. Converting the SNaN back to its real type
300  // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
301  if (!APF.isSignaling()) {
302  while (SVT != MVT::f32 && SVT != MVT::f16) {
303  SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
305  // Only do this if the target has a native EXTLOAD instruction from
306  // smaller type.
307  TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
308  TLI.ShouldShrinkFPConstant(OrigVT)) {
309  Type *SType = SVT.getTypeForEVT(*DAG.getContext());
310  LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
311  VT = SVT;
312  Extend = true;
313  }
314  }
315  }
316 
317  SDValue CPIdx =
318  DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
319  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
320  if (Extend) {
321  SDValue Result = DAG.getExtLoad(
322  ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
323  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
324  Alignment);
325  return Result;
326  }
327  SDValue Result = DAG.getLoad(
328  OrigVT, dl, DAG.getEntryNode(), CPIdx,
329  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
330  return Result;
331 }
332 
333 /// Expands the Constant node to a load from the constant pool.
334 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
335  SDLoc dl(CP);
336  EVT VT = CP->getValueType(0);
337  SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(),
338  TLI.getPointerTy(DAG.getDataLayout()));
339  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
340  SDValue Result = DAG.getLoad(
341  VT, dl, DAG.getEntryNode(), CPIdx,
342  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
343  return Result;
344 }
345 
346 /// Some target cannot handle a variable insertion index for the
347 /// INSERT_VECTOR_ELT instruction. In this case, it
348 /// is necessary to spill the vector being inserted into to memory, perform
349 /// the insert there, and then read the result back.
350 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
351  SDValue Val,
352  SDValue Idx,
353  const SDLoc &dl) {
354  SDValue Tmp1 = Vec;
355  SDValue Tmp2 = Val;
356  SDValue Tmp3 = Idx;
357 
358  // If the target doesn't support this, we have to spill the input vector
359  // to a temporary stack slot, update the element, then reload it. This is
360  // badness. We could also load the value into a vector register (either
361  // with a "move to register" or "extload into register" instruction, then
362  // permute it into place, if the idx is a constant and if the idx is
363  // supported by the target.
364  EVT VT = Tmp1.getValueType();
365  EVT EltVT = VT.getVectorElementType();
366  SDValue StackPtr = DAG.CreateStackTemporary(VT);
367 
368  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
369 
370  // Store the vector.
371  SDValue Ch = DAG.getStore(
372  DAG.getEntryNode(), dl, Tmp1, StackPtr,
373  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
374 
375  SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
376 
377  // Store the scalar value.
378  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT);
379  // Load the updated vector.
380  return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
381  DAG.getMachineFunction(), SPFI));
382 }
383 
384 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
385  SDValue Idx,
386  const SDLoc &dl) {
387  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
388  // SCALAR_TO_VECTOR requires that the type of the value being inserted
389  // match the element type of the vector being created, except for
390  // integers in which case the inserted value can be over width.
391  EVT EltVT = Vec.getValueType().getVectorElementType();
392  if (Val.getValueType() == EltVT ||
393  (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
394  SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
395  Vec.getValueType(), Val);
396 
397  unsigned NumElts = Vec.getValueType().getVectorNumElements();
398  // We generate a shuffle of InVec and ScVec, so the shuffle mask
399  // should be 0,1,2,3,4,5... with the appropriate element replaced with
400  // elt 0 of the RHS.
401  SmallVector<int, 8> ShufOps;
402  for (unsigned i = 0; i != NumElts; ++i)
403  ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
404 
405  return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
406  }
407  }
408  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
409 }
410 
411 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
412  LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
413  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
414  // FIXME: We shouldn't do this for TargetConstantFP's.
415  // FIXME: move this to the DAG Combiner! Note that we can't regress due
416  // to phase ordering between legalized code and the dag combiner. This
417  // probably means that we need to integrate dag combiner and legalizer
418  // together.
419  // We generally can't do this one for long doubles.
420  SDValue Chain = ST->getChain();
421  SDValue Ptr = ST->getBasePtr();
422  unsigned Alignment = ST->getAlignment();
423  MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
424  AAMDNodes AAInfo = ST->getAAInfo();
425  SDLoc dl(ST);
426  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
427  if (CFP->getValueType(0) == MVT::f32 &&
428  TLI.isTypeLegal(MVT::i32)) {
429  SDValue Con = DAG.getConstant(CFP->getValueAPF().
430  bitcastToAPInt().zextOrTrunc(32),
431  SDLoc(CFP), MVT::i32);
432  return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), Alignment,
433  MMOFlags, AAInfo);
434  }
435 
436  if (CFP->getValueType(0) == MVT::f64) {
437  // If this target supports 64-bit registers, do a single 64-bit store.
438  if (TLI.isTypeLegal(MVT::i64)) {
439  SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
440  zextOrTrunc(64), SDLoc(CFP), MVT::i64);
441  return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
442  Alignment, MMOFlags, AAInfo);
443  }
444 
445  if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
446  // Otherwise, if the target supports 32-bit registers, use 2 32-bit
447  // stores. If the target supports neither 32- nor 64-bits, this
448  // xform is certainly not worth it.
449  const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
450  SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
451  SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
452  if (DAG.getDataLayout().isBigEndian())
453  std::swap(Lo, Hi);
454 
455  Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), Alignment,
456  MMOFlags, AAInfo);
457  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
458  DAG.getConstant(4, dl, Ptr.getValueType()));
459  Hi = DAG.getStore(Chain, dl, Hi, Ptr,
460  ST->getPointerInfo().getWithOffset(4),
461  MinAlign(Alignment, 4U), MMOFlags, AAInfo);
462 
463  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
464  }
465  }
466  }
467  return SDValue(nullptr, 0);
468 }
469 
470 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
471  StoreSDNode *ST = cast<StoreSDNode>(Node);
472  SDValue Chain = ST->getChain();
473  SDValue Ptr = ST->getBasePtr();
474  SDLoc dl(Node);
475 
476  unsigned Alignment = ST->getAlignment();
477  MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
478  AAMDNodes AAInfo = ST->getAAInfo();
479 
480  if (!ST->isTruncatingStore()) {
481  LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
482  if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
483  ReplaceNode(ST, OptStore);
484  return;
485  }
486 
487  SDValue Value = ST->getValue();
488  MVT VT = Value.getSimpleValueType();
489  switch (TLI.getOperationAction(ISD::STORE, VT)) {
490  default: llvm_unreachable("This action is not supported yet!");
491  case TargetLowering::Legal: {
492  // If this is an unaligned store and the target doesn't support it,
493  // expand it.
494  EVT MemVT = ST->getMemoryVT();
495  const DataLayout &DL = DAG.getDataLayout();
496  if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
497  *ST->getMemOperand())) {
498  LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
499  SDValue Result = TLI.expandUnalignedStore(ST, DAG);
500  ReplaceNode(SDValue(ST, 0), Result);
501  } else
502  LLVM_DEBUG(dbgs() << "Legal store\n");
503  break;
504  }
505  case TargetLowering::Custom: {
506  LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
507  SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
508  if (Res && Res != SDValue(Node, 0))
509  ReplaceNode(SDValue(Node, 0), Res);
510  return;
511  }
513  MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
514  assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
515  "Can only promote stores to same size type");
516  Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
517  SDValue Result =
518  DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
519  Alignment, MMOFlags, AAInfo);
520  ReplaceNode(SDValue(Node, 0), Result);
521  break;
522  }
523  }
524  return;
525  }
526 
527  LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
528  SDValue Value = ST->getValue();
529  EVT StVT = ST->getMemoryVT();
530  unsigned StWidth = StVT.getSizeInBits();
531  auto &DL = DAG.getDataLayout();
532 
533  if (StWidth != StVT.getStoreSizeInBits()) {
534  // Promote to a byte-sized store with upper bits zero if not
535  // storing an integral number of bytes. For example, promote
536  // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
537  EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
538  StVT.getStoreSizeInBits());
539  Value = DAG.getZeroExtendInReg(Value, dl, StVT);
540  SDValue Result =
541  DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
542  Alignment, MMOFlags, AAInfo);
543  ReplaceNode(SDValue(Node, 0), Result);
544  } else if (StWidth & (StWidth - 1)) {
545  // If not storing a power-of-2 number of bits, expand as two stores.
546  assert(!StVT.isVector() && "Unsupported truncstore!");
547  unsigned LogStWidth = Log2_32(StWidth);
548  assert(LogStWidth < 32);
549  unsigned RoundWidth = 1 << LogStWidth;
550  assert(RoundWidth < StWidth);
551  unsigned ExtraWidth = StWidth - RoundWidth;
552  assert(ExtraWidth < RoundWidth);
553  assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
554  "Store size not an integral number of bytes!");
555  EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
556  EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
557  SDValue Lo, Hi;
558  unsigned IncrementSize;
559 
560  if (DL.isLittleEndian()) {
561  // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
562  // Store the bottom RoundWidth bits.
563  Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
564  RoundVT, Alignment, MMOFlags, AAInfo);
565 
566  // Store the remaining ExtraWidth bits.
567  IncrementSize = RoundWidth / 8;
568  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
569  DAG.getConstant(IncrementSize, dl,
570  Ptr.getValueType()));
571  Hi = DAG.getNode(
572  ISD::SRL, dl, Value.getValueType(), Value,
573  DAG.getConstant(RoundWidth, dl,
574  TLI.getShiftAmountTy(Value.getValueType(), DL)));
575  Hi = DAG.getTruncStore(
576  Chain, dl, Hi, Ptr,
577  ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
578  MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
579  } else {
580  // Big endian - avoid unaligned stores.
581  // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
582  // Store the top RoundWidth bits.
583  Hi = DAG.getNode(
584  ISD::SRL, dl, Value.getValueType(), Value,
585  DAG.getConstant(ExtraWidth, dl,
586  TLI.getShiftAmountTy(Value.getValueType(), DL)));
587  Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
588  RoundVT, Alignment, MMOFlags, AAInfo);
589 
590  // Store the remaining ExtraWidth bits.
591  IncrementSize = RoundWidth / 8;
592  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
593  DAG.getConstant(IncrementSize, dl,
594  Ptr.getValueType()));
595  Lo = DAG.getTruncStore(
596  Chain, dl, Value, Ptr,
597  ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
598  MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
599  }
600 
601  // The order of the stores doesn't matter.
602  SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
603  ReplaceNode(SDValue(Node, 0), Result);
604  } else {
605  switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
606  default: llvm_unreachable("This action is not supported yet!");
607  case TargetLowering::Legal: {
608  EVT MemVT = ST->getMemoryVT();
609  // If this is an unaligned store and the target doesn't support it,
610  // expand it.
611  if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
612  *ST->getMemOperand())) {
613  SDValue Result = TLI.expandUnalignedStore(ST, DAG);
614  ReplaceNode(SDValue(ST, 0), Result);
615  }
616  break;
617  }
618  case TargetLowering::Custom: {
619  SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
620  if (Res && Res != SDValue(Node, 0))
621  ReplaceNode(SDValue(Node, 0), Res);
622  return;
623  }
625  assert(!StVT.isVector() &&
626  "Vector Stores are handled in LegalizeVectorOps");
627 
628  SDValue Result;
629 
630  // TRUNCSTORE:i16 i32 -> STORE i16
631  if (TLI.isTypeLegal(StVT)) {
632  Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
633  Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
634  Alignment, MMOFlags, AAInfo);
635  } else {
636  // The in-memory type isn't legal. Truncate to the type it would promote
637  // to, and then do a truncstore.
638  Value = DAG.getNode(ISD::TRUNCATE, dl,
639  TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
640  Value);
641  Result = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
642  StVT, Alignment, MMOFlags, AAInfo);
643  }
644 
645  ReplaceNode(SDValue(Node, 0), Result);
646  break;
647  }
648  }
649 }
650 
651 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
652  LoadSDNode *LD = cast<LoadSDNode>(Node);
653  SDValue Chain = LD->getChain(); // The chain.
654  SDValue Ptr = LD->getBasePtr(); // The base pointer.
655  SDValue Value; // The value returned by the load op.
656  SDLoc dl(Node);
657 
659  if (ExtType == ISD::NON_EXTLOAD) {
660  LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
661  MVT VT = Node->getSimpleValueType(0);
662  SDValue RVal = SDValue(Node, 0);
663  SDValue RChain = SDValue(Node, 1);
664 
665  switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
666  default: llvm_unreachable("This action is not supported yet!");
667  case TargetLowering::Legal: {
668  EVT MemVT = LD->getMemoryVT();
669  const DataLayout &DL = DAG.getDataLayout();
670  // If this is an unaligned load and the target doesn't support it,
671  // expand it.
672  if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
673  *LD->getMemOperand())) {
674  std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
675  }
676  break;
677  }
679  if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
680  RVal = Res;
681  RChain = Res.getValue(1);
682  }
683  break;
684 
686  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
687  assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
688  "Can only promote loads to same size type");
689 
690  SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
691  RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
692  RChain = Res.getValue(1);
693  break;
694  }
695  }
696  if (RChain.getNode() != Node) {
697  assert(RVal.getNode() != Node && "Load must be completely replaced");
698  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
699  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
700  if (UpdatedNodes) {
701  UpdatedNodes->insert(RVal.getNode());
702  UpdatedNodes->insert(RChain.getNode());
703  }
704  ReplacedNode(Node);
705  }
706  return;
707  }
708 
709  LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
710  EVT SrcVT = LD->getMemoryVT();
711  unsigned SrcWidth = SrcVT.getSizeInBits();
712  unsigned Alignment = LD->getAlignment();
713  MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
714  AAMDNodes AAInfo = LD->getAAInfo();
715 
716  if (SrcWidth != SrcVT.getStoreSizeInBits() &&
717  // Some targets pretend to have an i1 loading operation, and actually
718  // load an i8. This trick is correct for ZEXTLOAD because the top 7
719  // bits are guaranteed to be zero; it helps the optimizers understand
720  // that these bits are zero. It is also useful for EXTLOAD, since it
721  // tells the optimizers that those bits are undefined. It would be
722  // nice to have an effective generic way of getting these benefits...
723  // Until such a way is found, don't insist on promoting i1 here.
724  (SrcVT != MVT::i1 ||
725  TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
727  // Promote to a byte-sized load if not loading an integral number of
728  // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
729  unsigned NewWidth = SrcVT.getStoreSizeInBits();
730  EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
731  SDValue Ch;
732 
733  // The extra bits are guaranteed to be zero, since we stored them that
734  // way. A zext load from NVT thus automatically gives zext from SrcVT.
735 
736  ISD::LoadExtType NewExtType =
738 
739  SDValue Result =
740  DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), Chain, Ptr,
741  LD->getPointerInfo(), NVT, Alignment, MMOFlags, AAInfo);
742 
743  Ch = Result.getValue(1); // The chain.
744 
745  if (ExtType == ISD::SEXTLOAD)
746  // Having the top bits zero doesn't help when sign extending.
747  Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
748  Result.getValueType(),
749  Result, DAG.getValueType(SrcVT));
750  else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
751  // All the top bits are guaranteed to be zero - inform the optimizers.
752  Result = DAG.getNode(ISD::AssertZext, dl,
753  Result.getValueType(), Result,
754  DAG.getValueType(SrcVT));
755 
756  Value = Result;
757  Chain = Ch;
758  } else if (SrcWidth & (SrcWidth - 1)) {
759  // If not loading a power-of-2 number of bits, expand as two loads.
760  assert(!SrcVT.isVector() && "Unsupported extload!");
761  unsigned LogSrcWidth = Log2_32(SrcWidth);
762  assert(LogSrcWidth < 32);
763  unsigned RoundWidth = 1 << LogSrcWidth;
764  assert(RoundWidth < SrcWidth);
765  unsigned ExtraWidth = SrcWidth - RoundWidth;
766  assert(ExtraWidth < RoundWidth);
767  assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
768  "Load size not an integral number of bytes!");
769  EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
770  EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
771  SDValue Lo, Hi, Ch;
772  unsigned IncrementSize;
773  auto &DL = DAG.getDataLayout();
774 
775  if (DL.isLittleEndian()) {
776  // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
777  // Load the bottom RoundWidth bits.
778  Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
779  LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
780  AAInfo);
781 
782  // Load the remaining ExtraWidth bits.
783  IncrementSize = RoundWidth / 8;
784  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
785  DAG.getConstant(IncrementSize, dl,
786  Ptr.getValueType()));
787  Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
788  LD->getPointerInfo().getWithOffset(IncrementSize),
789  ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
790  AAInfo);
791 
792  // Build a factor node to remember that this load is independent of
793  // the other one.
794  Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
795  Hi.getValue(1));
796 
797  // Move the top bits to the right place.
798  Hi = DAG.getNode(
799  ISD::SHL, dl, Hi.getValueType(), Hi,
800  DAG.getConstant(RoundWidth, dl,
801  TLI.getShiftAmountTy(Hi.getValueType(), DL)));
802 
803  // Join the hi and lo parts.
804  Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
805  } else {
806  // Big endian - avoid unaligned loads.
807  // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
808  // Load the top RoundWidth bits.
809  Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
810  LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
811  AAInfo);
812 
813  // Load the remaining ExtraWidth bits.
814  IncrementSize = RoundWidth / 8;
815  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
816  DAG.getConstant(IncrementSize, dl,
817  Ptr.getValueType()));
818  Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
819  LD->getPointerInfo().getWithOffset(IncrementSize),
820  ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
821  AAInfo);
822 
823  // Build a factor node to remember that this load is independent of
824  // the other one.
825  Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
826  Hi.getValue(1));
827 
828  // Move the top bits to the right place.
829  Hi = DAG.getNode(
830  ISD::SHL, dl, Hi.getValueType(), Hi,
831  DAG.getConstant(ExtraWidth, dl,
832  TLI.getShiftAmountTy(Hi.getValueType(), DL)));
833 
834  // Join the hi and lo parts.
835  Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
836  }
837 
838  Chain = Ch;
839  } else {
840  bool isCustom = false;
841  switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
842  SrcVT.getSimpleVT())) {
843  default: llvm_unreachable("This action is not supported yet!");
845  isCustom = true;
848  Value = SDValue(Node, 0);
849  Chain = SDValue(Node, 1);
850 
851  if (isCustom) {
852  if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
853  Value = Res;
854  Chain = Res.getValue(1);
855  }
856  } else {
857  // If this is an unaligned load and the target doesn't support it,
858  // expand it.
859  EVT MemVT = LD->getMemoryVT();
860  const DataLayout &DL = DAG.getDataLayout();
861  if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
862  *LD->getMemOperand())) {
863  std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
864  }
865  }
866  break;
867 
868  case TargetLowering::Expand: {
869  EVT DestVT = Node->getValueType(0);
870  if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
871  // If the source type is not legal, see if there is a legal extload to
872  // an intermediate type that we can then extend further.
873  EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
874  if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
875  TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
876  // If we are loading a legal type, this is a non-extload followed by a
877  // full extend.
878  ISD::LoadExtType MidExtType =
879  (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
880 
881  SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
882  SrcVT, LD->getMemOperand());
883  unsigned ExtendOp =
885  Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
886  Chain = Load.getValue(1);
887  break;
888  }
889 
890  // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
891  // normal undefined upper bits behavior to allow using an in-reg extend
892  // with the illegal FP type, so load as an integer and do the
893  // from-integer conversion.
894  if (SrcVT.getScalarType() == MVT::f16) {
895  EVT ISrcVT = SrcVT.changeTypeToInteger();
896  EVT IDestVT = DestVT.changeTypeToInteger();
897  EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
898 
899  SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT,
900  Chain, Ptr, ISrcVT,
901  LD->getMemOperand());
902  Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
903  Chain = Result.getValue(1);
904  break;
905  }
906  }
907 
908  assert(!SrcVT.isVector() &&
909  "Vector Loads are handled in LegalizeVectorOps");
910 
911  // FIXME: This does not work for vectors on most targets. Sign-
912  // and zero-extend operations are currently folded into extending
913  // loads, whether they are legal or not, and then we end up here
914  // without any support for legalizing them.
915  assert(ExtType != ISD::EXTLOAD &&
916  "EXTLOAD should always be supported!");
917  // Turn the unsupported load into an EXTLOAD followed by an
918  // explicit zero/sign extend inreg.
919  SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
920  Node->getValueType(0),
921  Chain, Ptr, SrcVT,
922  LD->getMemOperand());
923  SDValue ValRes;
924  if (ExtType == ISD::SEXTLOAD)
925  ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
926  Result.getValueType(),
927  Result, DAG.getValueType(SrcVT));
928  else
929  ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
930  Value = ValRes;
931  Chain = Result.getValue(1);
932  break;
933  }
934  }
935  }
936 
937  // Since loads produce two values, make sure to remember that we legalized
938  // both of them.
939  if (Chain.getNode() != Node) {
940  assert(Value.getNode() != Node && "Load must be completely replaced");
941  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
942  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
943  if (UpdatedNodes) {
944  UpdatedNodes->insert(Value.getNode());
945  UpdatedNodes->insert(Chain.getNode());
946  }
947  ReplacedNode(Node);
948  }
949 }
950 
951 /// Return a legal replacement for the given operation, with all legal operands.
952 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
953  LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
954 
955  // Allow illegal target nodes and illegal registers.
956  if (Node->getOpcode() == ISD::TargetConstant ||
957  Node->getOpcode() == ISD::Register)
958  return;
959 
960 #ifndef NDEBUG
961  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
962  assert((TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
964  TLI.isTypeLegal(Node->getValueType(i))) &&
965  "Unexpected illegal type!");
966 
967  for (const SDValue &Op : Node->op_values())
968  assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
970  TLI.isTypeLegal(Op.getValueType()) ||
971  Op.getOpcode() == ISD::TargetConstant ||
972  Op.getOpcode() == ISD::Register) &&
973  "Unexpected illegal type!");
974 #endif
975 
976  // Figure out the correct action; the way to query this varies by opcode
978  bool SimpleFinishLegalizing = true;
979  switch (Node->getOpcode()) {
982  case ISD::INTRINSIC_VOID:
983  case ISD::STACKSAVE:
984  Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
985  break;
987  Action = TLI.getOperationAction(Node->getOpcode(),
988  Node->getValueType(0));
989  break;
990  case ISD::VAARG:
991  Action = TLI.getOperationAction(Node->getOpcode(),
992  Node->getValueType(0));
993  if (Action != TargetLowering::Promote)
994  Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
995  break;
996  case ISD::FP_TO_FP16:
997  case ISD::SINT_TO_FP:
998  case ISD::UINT_TO_FP:
1000  case ISD::LROUND:
1001  case ISD::LLROUND:
1002  case ISD::LRINT:
1003  case ISD::LLRINT:
1004  Action = TLI.getOperationAction(Node->getOpcode(),
1005  Node->getOperand(0).getValueType());
1006  break;
1007  case ISD::FP_ROUND_INREG:
1008  case ISD::SIGN_EXTEND_INREG: {
1009  EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1010  Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1011  break;
1012  }
1013  case ISD::ATOMIC_STORE:
1014  Action = TLI.getOperationAction(Node->getOpcode(),
1015  Node->getOperand(2).getValueType());
1016  break;
1017  case ISD::SELECT_CC:
1018  case ISD::SETCC:
1019  case ISD::BR_CC: {
1020  unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1021  Node->getOpcode() == ISD::SETCC ? 2 : 1;
1022  unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1023  MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1024  ISD::CondCode CCCode =
1025  cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1026  Action = TLI.getCondCodeAction(CCCode, OpVT);
1027  if (Action == TargetLowering::Legal) {
1028  if (Node->getOpcode() == ISD::SELECT_CC)
1029  Action = TLI.getOperationAction(Node->getOpcode(),
1030  Node->getValueType(0));
1031  else
1032  Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1033  }
1034  break;
1035  }
1036  case ISD::LOAD:
1037  case ISD::STORE:
1038  // FIXME: Model these properly. LOAD and STORE are complicated, and
1039  // STORE expects the unlegalized operand in some cases.
1040  SimpleFinishLegalizing = false;
1041  break;
1042  case ISD::CALLSEQ_START:
1043  case ISD::CALLSEQ_END:
1044  // FIXME: This shouldn't be necessary. These nodes have special properties
1045  // dealing with the recursive nature of legalization. Removing this
1046  // special case should be done as part of making LegalizeDAG non-recursive.
1047  SimpleFinishLegalizing = false;
1048  break;
1049  case ISD::EXTRACT_ELEMENT:
1050  case ISD::FLT_ROUNDS_:
1051  case ISD::MERGE_VALUES:
1052  case ISD::EH_RETURN:
1054  case ISD::EH_DWARF_CFA:
1055  case ISD::EH_SJLJ_SETJMP:
1056  case ISD::EH_SJLJ_LONGJMP:
1058  // These operations lie about being legal: when they claim to be legal,
1059  // they should actually be expanded.
1060  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1061  if (Action == TargetLowering::Legal)
1062  Action = TargetLowering::Expand;
1063  break;
1064  case ISD::INIT_TRAMPOLINE:
1066  case ISD::FRAMEADDR:
1067  case ISD::RETURNADDR:
1068  case ISD::ADDROFRETURNADDR:
1069  case ISD::SPONENTRY:
1070  // These operations lie about being legal: when they claim to be legal,
1071  // they should actually be custom-lowered.
1072  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1073  if (Action == TargetLowering::Legal)
1074  Action = TargetLowering::Custom;
1075  break;
1076  case ISD::READCYCLECOUNTER:
1077  // READCYCLECOUNTER returns an i64, even if type legalization might have
1078  // expanded that to several smaller types.
1079  Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1080  break;
1081  case ISD::READ_REGISTER:
1082  case ISD::WRITE_REGISTER:
1083  // Named register is legal in the DAG, but blocked by register name
1084  // selection if not implemented by target (to chose the correct register)
1085  // They'll be converted to Copy(To/From)Reg.
1086  Action = TargetLowering::Legal;
1087  break;
1088  case ISD::DEBUGTRAP:
1089  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1090  if (Action == TargetLowering::Expand) {
1091  // replace ISD::DEBUGTRAP with ISD::TRAP
1092  SDValue NewVal;
1093  NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1094  Node->getOperand(0));
1095  ReplaceNode(Node, NewVal.getNode());
1096  LegalizeOp(NewVal.getNode());
1097  return;
1098  }
1099  break;
1100  case ISD::SADDSAT:
1101  case ISD::UADDSAT:
1102  case ISD::SSUBSAT:
1103  case ISD::USUBSAT: {
1104  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1105  break;
1106  }
1107  case ISD::SMULFIX:
1108  case ISD::SMULFIXSAT:
1109  case ISD::UMULFIX: {
1110  unsigned Scale = Node->getConstantOperandVal(2);
1111  Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1112  Node->getValueType(0), Scale);
1113  break;
1114  }
1115  case ISD::MSCATTER:
1116  Action = TLI.getOperationAction(Node->getOpcode(),
1117  cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1118  break;
1119  case ISD::MSTORE:
1120  Action = TLI.getOperationAction(Node->getOpcode(),
1121  cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1122  break;
1123  case ISD::VECREDUCE_FADD:
1124  case ISD::VECREDUCE_FMUL:
1125  case ISD::VECREDUCE_ADD:
1126  case ISD::VECREDUCE_MUL:
1127  case ISD::VECREDUCE_AND:
1128  case ISD::VECREDUCE_OR:
1129  case ISD::VECREDUCE_XOR:
1130  case ISD::VECREDUCE_SMAX:
1131  case ISD::VECREDUCE_SMIN:
1132  case ISD::VECREDUCE_UMAX:
1133  case ISD::VECREDUCE_UMIN:
1134  case ISD::VECREDUCE_FMAX:
1135  case ISD::VECREDUCE_FMIN:
1136  Action = TLI.getOperationAction(
1137  Node->getOpcode(), Node->getOperand(0).getValueType());
1138  break;
1139  default:
1140  if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1141  Action = TargetLowering::Legal;
1142  } else {
1143  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1144  }
1145  break;
1146  }
1147 
1148  if (SimpleFinishLegalizing) {
1149  SDNode *NewNode = Node;
1150  switch (Node->getOpcode()) {
1151  default: break;
1152  case ISD::SHL:
1153  case ISD::SRL:
1154  case ISD::SRA:
1155  case ISD::ROTL:
1156  case ISD::ROTR: {
1157  // Legalizing shifts/rotates requires adjusting the shift amount
1158  // to the appropriate width.
1159  SDValue Op0 = Node->getOperand(0);
1160  SDValue Op1 = Node->getOperand(1);
1161  if (!Op1.getValueType().isVector()) {
1162  SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1163  // The getShiftAmountOperand() may create a new operand node or
1164  // return the existing one. If new operand is created we need
1165  // to update the parent node.
1166  // Do not try to legalize SAO here! It will be automatically legalized
1167  // in the next round.
1168  if (SAO != Op1)
1169  NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1170  }
1171  }
1172  break;
1173  case ISD::FSHL:
1174  case ISD::FSHR:
1175  case ISD::SRL_PARTS:
1176  case ISD::SRA_PARTS:
1177  case ISD::SHL_PARTS: {
1178  // Legalizing shifts/rotates requires adjusting the shift amount
1179  // to the appropriate width.
1180  SDValue Op0 = Node->getOperand(0);
1181  SDValue Op1 = Node->getOperand(1);
1182  SDValue Op2 = Node->getOperand(2);
1183  if (!Op2.getValueType().isVector()) {
1184  SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1185  // The getShiftAmountOperand() may create a new operand node or
1186  // return the existing one. If new operand is created we need
1187  // to update the parent node.
1188  if (SAO != Op2)
1189  NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1190  }
1191  break;
1192  }
1193  }
1194 
1195  if (NewNode != Node) {
1196  ReplaceNode(Node, NewNode);
1197  Node = NewNode;
1198  }
1199  switch (Action) {
1200  case TargetLowering::Legal:
1201  LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1202  return;
1204  LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1205  // FIXME: The handling for custom lowering with multiple results is
1206  // a complete mess.
1207  if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1208  if (!(Res.getNode() != Node || Res.getResNo() != 0))
1209  return;
1210 
1211  if (Node->getNumValues() == 1) {
1212  LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1213  // We can just directly replace this node with the lowered value.
1214  ReplaceNode(SDValue(Node, 0), Res);
1215  return;
1216  }
1217 
1218  SmallVector<SDValue, 8> ResultVals;
1219  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1220  ResultVals.push_back(Res.getValue(i));
1221  LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1222  ReplaceNode(Node, ResultVals.data());
1223  return;
1224  }
1225  LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1228  if (ExpandNode(Node))
1229  return;
1232  ConvertNodeToLibcall(Node);
1233  return;
1235  PromoteNode(Node);
1236  return;
1237  }
1238  }
1239 
1240  switch (Node->getOpcode()) {
1241  default:
1242 #ifndef NDEBUG
1243  dbgs() << "NODE: ";
1244  Node->dump( &DAG);
1245  dbgs() << "\n";
1246 #endif
1247  llvm_unreachable("Do not know how to legalize this operator!");
1248 
1249  case ISD::CALLSEQ_START:
1250  case ISD::CALLSEQ_END:
1251  break;
1252  case ISD::LOAD:
1253  return LegalizeLoadOps(Node);
1254  case ISD::STORE:
1255  return LegalizeStoreOps(Node);
1256  }
1257 }
1258 
1259 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1260  SDValue Vec = Op.getOperand(0);
1261  SDValue Idx = Op.getOperand(1);
1262  SDLoc dl(Op);
1263 
1264  // Before we generate a new store to a temporary stack slot, see if there is
1265  // already one that we can use. There often is because when we scalarize
1266  // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1267  // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1268  // the vector. If all are expanded here, we don't want one store per vector
1269  // element.
1270 
1271  // Caches for hasPredecessorHelper
1274  Visited.insert(Op.getNode());
1275  Worklist.push_back(Idx.getNode());
1276  SDValue StackPtr, Ch;
1277  for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1278  UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1279  SDNode *User = *UI;
1280  if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1281  if (ST->isIndexed() || ST->isTruncatingStore() ||
1282  ST->getValue() != Vec)
1283  continue;
1284 
1285  // Make sure that nothing else could have stored into the destination of
1286  // this store.
1287  if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1288  continue;
1289 
1290  // If the index is dependent on the store we will introduce a cycle when
1291  // creating the load (the load uses the index, and by replacing the chain
1292  // we will make the index dependent on the load). Also, the store might be
1293  // dependent on the extractelement and introduce a cycle when creating
1294  // the load.
1295  if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1296  ST->hasPredecessor(Op.getNode()))
1297  continue;
1298 
1299  StackPtr = ST->getBasePtr();
1300  Ch = SDValue(ST, 0);
1301  break;
1302  }
1303  }
1304 
1305  EVT VecVT = Vec.getValueType();
1306 
1307  if (!Ch.getNode()) {
1308  // Store the value to a temporary stack slot, then LOAD the returned part.
1309  StackPtr = DAG.CreateStackTemporary(VecVT);
1310  Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1311  MachinePointerInfo());
1312  }
1313 
1314  StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1315 
1316  SDValue NewLoad;
1317 
1318  if (Op.getValueType().isVector())
1319  NewLoad =
1320  DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
1321  else
1322  NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1324  VecVT.getVectorElementType());
1325 
1326  // Replace the chain going out of the store, by the one out of the load.
1327  DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1328 
1329  // We introduced a cycle though, so update the loads operands, making sure
1330  // to use the original store's chain as an incoming chain.
1331  SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1332  NewLoad->op_end());
1333  NewLoadOperands[0] = Ch;
1334  NewLoad =
1335  SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1336  return NewLoad;
1337 }
1338 
1339 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1340  assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1341 
1342  SDValue Vec = Op.getOperand(0);
1343  SDValue Part = Op.getOperand(1);
1344  SDValue Idx = Op.getOperand(2);
1345  SDLoc dl(Op);
1346 
1347  // Store the value to a temporary stack slot, then LOAD the returned part.
1348  EVT VecVT = Vec.getValueType();
1349  SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1350  int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1351  MachinePointerInfo PtrInfo =
1352  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1353 
1354  // First store the whole vector.
1355  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1356 
1357  // Then store the inserted part.
1358  SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1359 
1360  // Store the subvector.
1361  Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, MachinePointerInfo());
1362 
1363  // Finally, load the updated vector.
1364  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
1365 }
1366 
1367 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1368  // We can't handle this case efficiently. Allocate a sufficiently
1369  // aligned object on the stack, store each element into it, then load
1370  // the result as a vector.
1371  // Create the stack frame object.
1372  EVT VT = Node->getValueType(0);
1373  EVT EltVT = VT.getVectorElementType();
1374  SDLoc dl(Node);
1375  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1376  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1377  MachinePointerInfo PtrInfo =
1378  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1379 
1380  // Emit a store of each element to the stack slot.
1381  SmallVector<SDValue, 8> Stores;
1382  unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1383  assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1384  // Store (in the right endianness) the elements to memory.
1385  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1386  // Ignore undef elements.
1387  if (Node->getOperand(i).isUndef()) continue;
1388 
1389  unsigned Offset = TypeByteSize*i;
1390 
1391  SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType());
1392  Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1393 
1394  // If the destination vector element type is narrower than the source
1395  // element type, only store the bits necessary.
1396  if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1397  Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1398  Node->getOperand(i), Idx,
1399  PtrInfo.getWithOffset(Offset), EltVT));
1400  } else
1401  Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1402  Idx, PtrInfo.getWithOffset(Offset)));
1403  }
1404 
1405  SDValue StoreChain;
1406  if (!Stores.empty()) // Not all undef elements?
1407  StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1408  else
1409  StoreChain = DAG.getEntryNode();
1410 
1411  // Result is a load from the stack slot.
1412  return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1413 }
1414 
1415 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1416 /// containing the sign bit if the target has no integer value capable of
1417 /// holding all bits of the floating-point value.
1418 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1419  const SDLoc &DL,
1420  SDValue Value) const {
1421  EVT FloatVT = Value.getValueType();
1422  unsigned NumBits = FloatVT.getSizeInBits();
1423  State.FloatVT = FloatVT;
1424  EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1425  // Convert to an integer of the same size.
1426  if (TLI.isTypeLegal(IVT)) {
1427  State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1428  State.SignMask = APInt::getSignMask(NumBits);
1429  State.SignBit = NumBits - 1;
1430  return;
1431  }
1432 
1433  auto &DataLayout = DAG.getDataLayout();
1434  // Store the float to memory, then load the sign part out as an integer.
1435  MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1436  // First create a temporary that is aligned for both the load and store.
1437  SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1438  int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1439  // Then store the float to it.
1440  State.FloatPtr = StackPtr;
1441  MachineFunction &MF = DAG.getMachineFunction();
1442  State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1443  State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1444  State.FloatPointerInfo);
1445 
1446  SDValue IntPtr;
1447  if (DataLayout.isBigEndian()) {
1448  assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1449  // Load out a legal integer with the same sign bit as the float.
1450  IntPtr = StackPtr;
1451  State.IntPointerInfo = State.FloatPointerInfo;
1452  } else {
1453  // Advance the pointer so that the loaded byte will contain the sign bit.
1454  unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1;
1455  IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
1456  DAG.getConstant(ByteOffset, DL, StackPtr.getValueType()));
1457  State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1458  ByteOffset);
1459  }
1460 
1461  State.IntPtr = IntPtr;
1462  State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1463  State.IntPointerInfo, MVT::i8);
1464  State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7);
1465  State.SignBit = 7;
1466 }
1467 
1468 /// Replace the integer value produced by getSignAsIntValue() with a new value
1469 /// and cast the result back to a floating-point type.
1470 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1471  const SDLoc &DL,
1472  SDValue NewIntValue) const {
1473  if (!State.Chain)
1474  return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1475 
1476  // Override the part containing the sign bit in the value stored on the stack.
1477  SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1478  State.IntPointerInfo, MVT::i8);
1479  return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1480  State.FloatPointerInfo);
1481 }
1482 
1483 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1484  SDLoc DL(Node);
1485  SDValue Mag = Node->getOperand(0);
1486  SDValue Sign = Node->getOperand(1);
1487 
1488  // Get sign bit into an integer value.
1489  FloatSignAsInt SignAsInt;
1490  getSignAsIntValue(SignAsInt, DL, Sign);
1491 
1492  EVT IntVT = SignAsInt.IntValue.getValueType();
1493  SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1494  SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1495  SignMask);
1496 
1497  // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1498  EVT FloatVT = Mag.getValueType();
1499  if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1500  TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1501  SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1502  SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1503  SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1504  DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1505  return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1506  }
1507 
1508  // Transform Mag value to integer, and clear the sign bit.
1509  FloatSignAsInt MagAsInt;
1510  getSignAsIntValue(MagAsInt, DL, Mag);
1511  EVT MagVT = MagAsInt.IntValue.getValueType();
1512  SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1513  SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1514  ClearSignMask);
1515 
1516  // Get the signbit at the right position for MagAsInt.
1517  int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1518  EVT ShiftVT = IntVT;
1519  if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) {
1520  SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1521  ShiftVT = MagVT;
1522  }
1523  if (ShiftAmount > 0) {
1524  SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1525  SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1526  } else if (ShiftAmount < 0) {
1527  SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1528  SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1529  }
1530  if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) {
1531  SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1532  }
1533 
1534  // Store the part with the modified sign and convert back to float.
1535  SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
1536  return modifySignAsInt(MagAsInt, DL, CopiedSign);
1537 }
1538 
1539 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1540  SDLoc DL(Node);
1541  SDValue Value = Node->getOperand(0);
1542 
1543  // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1544  EVT FloatVT = Value.getValueType();
1545  if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1546  SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1547  return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1548  }
1549 
1550  // Transform value to integer, clear the sign bit and transform back.
1551  FloatSignAsInt ValueAsInt;
1552  getSignAsIntValue(ValueAsInt, DL, Value);
1553  EVT IntVT = ValueAsInt.IntValue.getValueType();
1554  SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1555  SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1556  ClearSignMask);
1557  return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1558 }
1559 
1560 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1562  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1563  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1564  " not tell us which reg is the stack pointer!");
1565  SDLoc dl(Node);
1566  EVT VT = Node->getValueType(0);
1567  SDValue Tmp1 = SDValue(Node, 0);
1568  SDValue Tmp2 = SDValue(Node, 1);
1569  SDValue Tmp3 = Node->getOperand(2);
1570  SDValue Chain = Tmp1.getOperand(0);
1571 
1572  // Chain the dynamic stack allocation so that it doesn't modify the stack
1573  // pointer when other instructions are using the stack.
1574  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1575 
1576  SDValue Size = Tmp2.getOperand(1);
1577  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1578  Chain = SP.getValue(1);
1579  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1580  unsigned StackAlign =
1581  DAG.getSubtarget().getFrameLowering()->getStackAlignment();
1582  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1583  if (Align > StackAlign)
1584  Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1585  DAG.getConstant(-(uint64_t)Align, dl, VT));
1586  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1587 
1588  Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1589  DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1590 
1591  Results.push_back(Tmp1);
1592  Results.push_back(Tmp2);
1593 }
1594 
1595 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
1596 /// target.
1597 ///
1598 /// If the SETCC has been legalized using AND / OR, then the legalized node
1599 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1600 /// will be set to false.
1601 ///
1602 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1603 /// then the values of LHS and RHS will be swapped, CC will be set to the
1604 /// new condition, and NeedInvert will be set to false.
1605 ///
1606 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1607 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1608 /// will be set to true. The caller must invert the result of the SETCC with
1609 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1610 /// of a true/false result.
1611 ///
1612 /// \returns true if the SetCC has been legalized, false if it hasn't.
1613 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS,
1614  SDValue &RHS, SDValue &CC,
1615  bool &NeedInvert,
1616  const SDLoc &dl) {
1617  MVT OpVT = LHS.getSimpleValueType();
1618  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1619  NeedInvert = false;
1620  bool NeedSwap = false;
1621  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1622  default: llvm_unreachable("Unknown condition code action!");
1623  case TargetLowering::Legal:
1624  // Nothing to do.
1625  break;
1626  case TargetLowering::Expand: {
1628  if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1629  std::swap(LHS, RHS);
1630  CC = DAG.getCondCode(InvCC);
1631  return true;
1632  }
1633  // Swapping operands didn't work. Try inverting the condition.
1634  InvCC = getSetCCInverse(CCCode, OpVT.isInteger());
1635  if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1636  // If inverting the condition is not enough, try swapping operands
1637  // on top of it.
1638  InvCC = ISD::getSetCCSwappedOperands(InvCC);
1639  NeedSwap = true;
1640  }
1641  if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1642  CC = DAG.getCondCode(InvCC);
1643  NeedInvert = true;
1644  if (NeedSwap)
1645  std::swap(LHS, RHS);
1646  return true;
1647  }
1648 
1650  unsigned Opc = 0;
1651  switch (CCCode) {
1652  default: llvm_unreachable("Don't know how to expand this condition!");
1653  case ISD::SETO:
1654  assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT)
1655  && "If SETO is expanded, SETOEQ must be legal!");
1656  CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1657  case ISD::SETUO:
1658  assert(TLI.isCondCodeLegal(ISD::SETUNE, OpVT)
1659  && "If SETUO is expanded, SETUNE must be legal!");
1660  CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1661  case ISD::SETOEQ:
1662  case ISD::SETOGT:
1663  case ISD::SETOGE:
1664  case ISD::SETOLT:
1665  case ISD::SETOLE:
1666  case ISD::SETONE:
1667  case ISD::SETUEQ:
1668  case ISD::SETUNE:
1669  case ISD::SETUGT:
1670  case ISD::SETUGE:
1671  case ISD::SETULT:
1672  case ISD::SETULE:
1673  // If we are floating point, assign and break, otherwise fall through.
1674  if (!OpVT.isInteger()) {
1675  // We can use the 4th bit to tell if we are the unordered
1676  // or ordered version of the opcode.
1677  CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1678  Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1679  CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1680  break;
1681  }
1682  // Fallthrough if we are unsigned integer.
1684  case ISD::SETLE:
1685  case ISD::SETGT:
1686  case ISD::SETGE:
1687  case ISD::SETLT:
1688  case ISD::SETNE:
1689  case ISD::SETEQ:
1690  // If all combinations of inverting the condition and swapping operands
1691  // didn't work then we have no means to expand the condition.
1692  llvm_unreachable("Don't know how to expand this condition!");
1693  }
1694 
1695  SDValue SetCC1, SetCC2;
1696  if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1697  // If we aren't the ordered or unorder operation,
1698  // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1699  SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1700  SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1701  } else {
1702  // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1703  SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1704  SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1705  }
1706  LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1707  RHS = SDValue();
1708  CC = SDValue();
1709  return true;
1710  }
1711  }
1712  return false;
1713 }
1714 
1715 /// Emit a store/load combination to the stack. This stores
1716 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1717 /// a load from the stack slot to DestVT, extending it if needed.
1718 /// The resultant code need not be legal.
1719 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1720  EVT DestVT, const SDLoc &dl) {
1721  return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1722 }
1723 
1724 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1725  EVT DestVT, const SDLoc &dl,
1726  SDValue Chain) {
1727  // Create the stack frame object.
1728  unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
1729  SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1730  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1731 
1732  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1733  int SPFI = StackPtrFI->getIndex();
1734  MachinePointerInfo PtrInfo =
1735  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1736 
1737  unsigned SrcSize = SrcOp.getValueSizeInBits();
1738  unsigned SlotSize = SlotVT.getSizeInBits();
1739  unsigned DestSize = DestVT.getSizeInBits();
1740  Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1741  unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
1742 
1743  // Emit a store to the stack slot. Use a truncstore if the input value is
1744  // later than DestVT.
1745  SDValue Store;
1746 
1747  if (SrcSize > SlotSize)
1748  Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
1749  SlotVT, SrcAlign);
1750  else {
1751  assert(SrcSize == SlotSize && "Invalid store");
1752  Store =
1753  DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1754  }
1755 
1756  // Result is a load from the stack slot.
1757  if (SlotSize == DestSize)
1758  return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1759 
1760  assert(SlotSize < DestSize && "Unknown extension!");
1761  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1762  DestAlign);
1763 }
1764 
1765 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1766  SDLoc dl(Node);
1767  // Create a vector sized/aligned stack slot, store the value to element #0,
1768  // then load the whole vector back out.
1769  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1770 
1771  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1772  int SPFI = StackPtrFI->getIndex();
1773 
1774  SDValue Ch = DAG.getTruncStore(
1775  DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1776  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1777  Node->getValueType(0).getVectorElementType());
1778  return DAG.getLoad(
1779  Node->getValueType(0), dl, Ch, StackPtr,
1780  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
1781 }
1782 
1783 static bool
1785  const TargetLowering &TLI, SDValue &Res) {
1786  unsigned NumElems = Node->getNumOperands();
1787  SDLoc dl(Node);
1788  EVT VT = Node->getValueType(0);
1789 
1790  // Try to group the scalars into pairs, shuffle the pairs together, then
1791  // shuffle the pairs of pairs together, etc. until the vector has
1792  // been built. This will work only if all of the necessary shuffle masks
1793  // are legal.
1794 
1795  // We do this in two phases; first to check the legality of the shuffles,
1796  // and next, assuming that all shuffles are legal, to create the new nodes.
1797  for (int Phase = 0; Phase < 2; ++Phase) {
1799  NewIntermedVals;
1800  for (unsigned i = 0; i < NumElems; ++i) {
1801  SDValue V = Node->getOperand(i);
1802  if (V.isUndef())
1803  continue;
1804 
1805  SDValue Vec;
1806  if (Phase)
1807  Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1808  IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1809  }
1810 
1811  while (IntermedVals.size() > 2) {
1812  NewIntermedVals.clear();
1813  for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1814  // This vector and the next vector are shuffled together (simply to
1815  // append the one to the other).
1816  SmallVector<int, 16> ShuffleVec(NumElems, -1);
1817 
1818  SmallVector<int, 16> FinalIndices;
1819  FinalIndices.reserve(IntermedVals[i].second.size() +
1820  IntermedVals[i+1].second.size());
1821 
1822  int k = 0;
1823  for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1824  ++j, ++k) {
1825  ShuffleVec[k] = j;
1826  FinalIndices.push_back(IntermedVals[i].second[j]);
1827  }
1828  for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1829  ++j, ++k) {
1830  ShuffleVec[k] = NumElems + j;
1831  FinalIndices.push_back(IntermedVals[i+1].second[j]);
1832  }
1833 
1834  SDValue Shuffle;
1835  if (Phase)
1836  Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1837  IntermedVals[i+1].first,
1838  ShuffleVec);
1839  else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1840  return false;
1841  NewIntermedVals.push_back(
1842  std::make_pair(Shuffle, std::move(FinalIndices)));
1843  }
1844 
1845  // If we had an odd number of defined values, then append the last
1846  // element to the array of new vectors.
1847  if ((IntermedVals.size() & 1) != 0)
1848  NewIntermedVals.push_back(IntermedVals.back());
1849 
1850  IntermedVals.swap(NewIntermedVals);
1851  }
1852 
1853  assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1854  "Invalid number of intermediate vectors");
1855  SDValue Vec1 = IntermedVals[0].first;
1856  SDValue Vec2;
1857  if (IntermedVals.size() > 1)
1858  Vec2 = IntermedVals[1].first;
1859  else if (Phase)
1860  Vec2 = DAG.getUNDEF(VT);
1861 
1862  SmallVector<int, 16> ShuffleVec(NumElems, -1);
1863  for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1864  ShuffleVec[IntermedVals[0].second[i]] = i;
1865  for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1866  ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1867 
1868  if (Phase)
1869  Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1870  else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1871  return false;
1872  }
1873 
1874  return true;
1875 }
1876 
1877 /// Expand a BUILD_VECTOR node on targets that don't
1878 /// support the operation, but do support the resultant vector type.
1879 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1880  unsigned NumElems = Node->getNumOperands();
1881  SDValue Value1, Value2;
1882  SDLoc dl(Node);
1883  EVT VT = Node->getValueType(0);
1884  EVT OpVT = Node->getOperand(0).getValueType();
1885  EVT EltVT = VT.getVectorElementType();
1886 
1887  // If the only non-undef value is the low element, turn this into a
1888  // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1889  bool isOnlyLowElement = true;
1890  bool MoreThanTwoValues = false;
1891  bool isConstant = true;
1892  for (unsigned i = 0; i < NumElems; ++i) {
1893  SDValue V = Node->getOperand(i);
1894  if (V.isUndef())
1895  continue;
1896  if (i > 0)
1897  isOnlyLowElement = false;
1898  if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1899  isConstant = false;
1900 
1901  if (!Value1.getNode()) {
1902  Value1 = V;
1903  } else if (!Value2.getNode()) {
1904  if (V != Value1)
1905  Value2 = V;
1906  } else if (V != Value1 && V != Value2) {
1907  MoreThanTwoValues = true;
1908  }
1909  }
1910 
1911  if (!Value1.getNode())
1912  return DAG.getUNDEF(VT);
1913 
1914  if (isOnlyLowElement)
1915  return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1916 
1917  // If all elements are constants, create a load from the constant pool.
1918  if (isConstant) {
1920  for (unsigned i = 0, e = NumElems; i != e; ++i) {
1921  if (ConstantFPSDNode *V =
1922  dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1923  CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1924  } else if (ConstantSDNode *V =
1925  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1926  if (OpVT==EltVT)
1927  CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1928  else {
1929  // If OpVT and EltVT don't match, EltVT is not legal and the
1930  // element values have been promoted/truncated earlier. Undo this;
1931  // we don't want a v16i8 to become a v16i32 for example.
1932  const ConstantInt *CI = V->getConstantIntValue();
1933  CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1934  CI->getZExtValue()));
1935  }
1936  } else {
1937  assert(Node->getOperand(i).isUndef());
1938  Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1939  CV.push_back(UndefValue::get(OpNTy));
1940  }
1941  }
1942  Constant *CP = ConstantVector::get(CV);
1943  SDValue CPIdx =
1944  DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
1945  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1946  return DAG.getLoad(
1947  VT, dl, DAG.getEntryNode(), CPIdx,
1948  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
1949  Alignment);
1950  }
1951 
1952  SmallSet<SDValue, 16> DefinedValues;
1953  for (unsigned i = 0; i < NumElems; ++i) {
1954  if (Node->getOperand(i).isUndef())
1955  continue;
1956  DefinedValues.insert(Node->getOperand(i));
1957  }
1958 
1959  if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1960  if (!MoreThanTwoValues) {
1961  SmallVector<int, 8> ShuffleVec(NumElems, -1);
1962  for (unsigned i = 0; i < NumElems; ++i) {
1963  SDValue V = Node->getOperand(i);
1964  if (V.isUndef())
1965  continue;
1966  ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1967  }
1968  if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1969  // Get the splatted value into the low element of a vector register.
1970  SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1971  SDValue Vec2;
1972  if (Value2.getNode())
1973  Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1974  else
1975  Vec2 = DAG.getUNDEF(VT);
1976 
1977  // Return shuffle(LowValVec, undef, <0,0,0,0>)
1978  return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1979  }
1980  } else {
1981  SDValue Res;
1982  if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
1983  return Res;
1984  }
1985  }
1986 
1987  // Otherwise, we can't handle this case efficiently.
1988  return ExpandVectorBuildThroughStack(Node);
1989 }
1990 
1991 // Expand a node into a call to a libcall. If the result value
1992 // does not fit into a register, return the lo part and set the hi part to the
1993 // by-reg argument. If it does fit into a single register, return the result
1994 // and leave the Hi part unset.
1995 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1996  bool isSigned) {
1998  TargetLowering::ArgListEntry Entry;
1999  for (const SDValue &Op : Node->op_values()) {
2000  EVT ArgVT = Op.getValueType();
2001  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2002  Entry.Node = Op;
2003  Entry.Ty = ArgTy;
2004  Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2005  Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2006  Args.push_back(Entry);
2007  }
2008  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2009  TLI.getPointerTy(DAG.getDataLayout()));
2010 
2011  EVT RetVT = Node->getValueType(0);
2012  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2013 
2014  // By default, the input chain to this libcall is the entry node of the
2015  // function. If the libcall is going to be emitted as a tail call then
2016  // TLI.isUsedByReturnOnly will change it to the right chain if the return
2017  // node which is being folded has a non-entry input chain.
2018  SDValue InChain = DAG.getEntryNode();
2019 
2020  // isTailCall may be true since the callee does not reference caller stack
2021  // frame. Check if it's in the right position and that the return types match.
2022  SDValue TCChain = InChain;
2023  const Function &F = DAG.getMachineFunction().getFunction();
2024  bool isTailCall =
2025  TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2026  (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
2027  if (isTailCall)
2028  InChain = TCChain;
2029 
2031  bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
2032  CLI.setDebugLoc(SDLoc(Node))
2033  .setChain(InChain)
2034  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2035  std::move(Args))
2036  .setTailCall(isTailCall)
2037  .setSExtResult(signExtend)
2038  .setZExtResult(!signExtend)
2040 
2041  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2042 
2043  if (!CallInfo.second.getNode()) {
2044  LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump());
2045  // It's a tailcall, return the chain (which is the DAG root).
2046  return DAG.getRoot();
2047  }
2048 
2049  LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump());
2050  return CallInfo.first;
2051 }
2052 
2053 // Expand a node into a call to a libcall. Similar to
2054 // ExpandLibCall except that the first operand is the in-chain.
2055 std::pair<SDValue, SDValue>
2056 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2057  SDNode *Node,
2058  bool isSigned) {
2059  SDValue InChain = Node->getOperand(0);
2060 
2062  TargetLowering::ArgListEntry Entry;
2063  for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2064  EVT ArgVT = Node->getOperand(i).getValueType();
2065  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2066  Entry.Node = Node->getOperand(i);
2067  Entry.Ty = ArgTy;
2068  Entry.IsSExt = isSigned;
2069  Entry.IsZExt = !isSigned;
2070  Args.push_back(Entry);
2071  }
2072  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2073  TLI.getPointerTy(DAG.getDataLayout()));
2074 
2075  Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2076 
2078  CLI.setDebugLoc(SDLoc(Node))
2079  .setChain(InChain)
2080  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2081  std::move(Args))
2082  .setSExtResult(isSigned)
2083  .setZExtResult(!isSigned);
2084 
2085  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2086 
2087  return CallInfo;
2088 }
2089 
2090 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2091  RTLIB::Libcall Call_F32,
2092  RTLIB::Libcall Call_F64,
2093  RTLIB::Libcall Call_F80,
2094  RTLIB::Libcall Call_F128,
2095  RTLIB::Libcall Call_PPCF128) {
2096  if (Node->isStrictFPOpcode())
2097  Node = DAG.mutateStrictFPToFP(Node);
2098 
2099  RTLIB::Libcall LC;
2100  switch (Node->getSimpleValueType(0).SimpleTy) {
2101  default: llvm_unreachable("Unexpected request for libcall!");
2102  case MVT::f32: LC = Call_F32; break;
2103  case MVT::f64: LC = Call_F64; break;
2104  case MVT::f80: LC = Call_F80; break;
2105  case MVT::f128: LC = Call_F128; break;
2106  case MVT::ppcf128: LC = Call_PPCF128; break;
2107  }
2108  return ExpandLibCall(LC, Node, false);
2109 }
2110 
2111 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2112  RTLIB::Libcall Call_I8,
2113  RTLIB::Libcall Call_I16,
2114  RTLIB::Libcall Call_I32,
2115  RTLIB::Libcall Call_I64,
2116  RTLIB::Libcall Call_I128) {
2117  RTLIB::Libcall LC;
2118  switch (Node->getSimpleValueType(0).SimpleTy) {
2119  default: llvm_unreachable("Unexpected request for libcall!");
2120  case MVT::i8: LC = Call_I8; break;
2121  case MVT::i16: LC = Call_I16; break;
2122  case MVT::i32: LC = Call_I32; break;
2123  case MVT::i64: LC = Call_I64; break;
2124  case MVT::i128: LC = Call_I128; break;
2125  }
2126  return ExpandLibCall(LC, Node, isSigned);
2127 }
2128 
2129 /// Expand the node to a libcall based on first argument type (for instance
2130 /// lround and its variant).
2131 SDValue SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2132  RTLIB::Libcall Call_F32,
2133  RTLIB::Libcall Call_F64,
2134  RTLIB::Libcall Call_F80,
2135  RTLIB::Libcall Call_F128,
2136  RTLIB::Libcall Call_PPCF128) {
2137  RTLIB::Libcall LC;
2138  switch (Node->getOperand(0).getValueType().getSimpleVT().SimpleTy) {
2139  default: llvm_unreachable("Unexpected request for libcall!");
2140  case MVT::f32: LC = Call_F32; break;
2141  case MVT::f64: LC = Call_F64; break;
2142  case MVT::f80: LC = Call_F80; break;
2143  case MVT::f128: LC = Call_F128; break;
2144  case MVT::ppcf128: LC = Call_PPCF128; break;
2145  }
2146 
2147  return ExpandLibCall(LC, Node, false);
2148 }
2149 
2150 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2151 void
2152 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2153  SmallVectorImpl<SDValue> &Results) {
2154  unsigned Opcode = Node->getOpcode();
2155  bool isSigned = Opcode == ISD::SDIVREM;
2156 
2157  RTLIB::Libcall LC;
2158  switch (Node->getSimpleValueType(0).SimpleTy) {
2159  default: llvm_unreachable("Unexpected request for libcall!");
2160  case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2161  case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2162  case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2163  case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2164  case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2165  }
2166 
2167  // The input chain to this libcall is the entry node of the function.
2168  // Legalizing the call will automatically add the previous call to the
2169  // dependence.
2170  SDValue InChain = DAG.getEntryNode();
2171 
2172  EVT RetVT = Node->getValueType(0);
2173  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2174 
2176  TargetLowering::ArgListEntry Entry;
2177  for (const SDValue &Op : Node->op_values()) {
2178  EVT ArgVT = Op.getValueType();
2179  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2180  Entry.Node = Op;
2181  Entry.Ty = ArgTy;
2182  Entry.IsSExt = isSigned;
2183  Entry.IsZExt = !isSigned;
2184  Args.push_back(Entry);
2185  }
2186 
2187  // Also pass the return address of the remainder.
2188  SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2189  Entry.Node = FIPtr;
2190  Entry.Ty = RetTy->getPointerTo();
2191  Entry.IsSExt = isSigned;
2192  Entry.IsZExt = !isSigned;
2193  Args.push_back(Entry);
2194 
2195  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2196  TLI.getPointerTy(DAG.getDataLayout()));
2197 
2198  SDLoc dl(Node);
2200  CLI.setDebugLoc(dl)
2201  .setChain(InChain)
2202  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2203  std::move(Args))
2204  .setSExtResult(isSigned)
2205  .setZExtResult(!isSigned);
2206 
2207  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2208 
2209  // Remainder is loaded back from the stack frame.
2210  SDValue Rem =
2211  DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
2212  Results.push_back(CallInfo.first);
2213  Results.push_back(Rem);
2214 }
2215 
2216 /// Return true if sincos libcall is available.
2217 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2218  RTLIB::Libcall LC;
2219  switch (Node->getSimpleValueType(0).SimpleTy) {
2220  default: llvm_unreachable("Unexpected request for libcall!");
2221  case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2222  case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2223  case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2224  case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2225  case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2226  }
2227  return TLI.getLibcallName(LC) != nullptr;
2228 }
2229 
2230 /// Only issue sincos libcall if both sin and cos are needed.
2231 static bool useSinCos(SDNode *Node) {
2232  unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2233  ? ISD::FCOS : ISD::FSIN;
2234 
2235  SDValue Op0 = Node->getOperand(0);
2236  for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2237  UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2238  SDNode *User = *UI;
2239  if (User == Node)
2240  continue;
2241  // The other user might have been turned into sincos already.
2242  if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2243  return true;
2244  }
2245  return false;
2246 }
2247 
2248 /// Issue libcalls to sincos to compute sin / cos pairs.
2249 void
2250 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2251  SmallVectorImpl<SDValue> &Results) {
2252  RTLIB::Libcall LC;
2253  switch (Node->getSimpleValueType(0).SimpleTy) {
2254  default: llvm_unreachable("Unexpected request for libcall!");
2255  case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2256  case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2257  case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2258  case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2259  case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2260  }
2261 
2262  // The input chain to this libcall is the entry node of the function.
2263  // Legalizing the call will automatically add the previous call to the
2264  // dependence.
2265  SDValue InChain = DAG.getEntryNode();
2266 
2267  EVT RetVT = Node->getValueType(0);
2268  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2269 
2271  TargetLowering::ArgListEntry Entry;
2272 
2273  // Pass the argument.
2274  Entry.Node = Node->getOperand(0);
2275  Entry.Ty = RetTy;
2276  Entry.IsSExt = false;
2277  Entry.IsZExt = false;
2278  Args.push_back(Entry);
2279 
2280  // Pass the return address of sin.
2281  SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2282  Entry.Node = SinPtr;
2283  Entry.Ty = RetTy->getPointerTo();
2284  Entry.IsSExt = false;
2285  Entry.IsZExt = false;
2286  Args.push_back(Entry);
2287 
2288  // Also pass the return address of the cos.
2289  SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2290  Entry.Node = CosPtr;
2291  Entry.Ty = RetTy->getPointerTo();
2292  Entry.IsSExt = false;
2293  Entry.IsZExt = false;
2294  Args.push_back(Entry);
2295 
2296  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2297  TLI.getPointerTy(DAG.getDataLayout()));
2298 
2299  SDLoc dl(Node);
2301  CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
2302  TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
2303  std::move(Args));
2304 
2305  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2306 
2307  Results.push_back(
2308  DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
2309  Results.push_back(
2310  DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
2311 }
2312 
2313 /// This function is responsible for legalizing a
2314 /// INT_TO_FP operation of the specified operand when the target requests that
2315 /// we expand it. At this point, we know that the result and operand types are
2316 /// legal for the target.
2317 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0,
2318  EVT DestVT,
2319  const SDLoc &dl) {
2320  EVT SrcVT = Op0.getValueType();
2321 
2322  // TODO: Should any fast-math-flags be set for the created nodes?
2323  LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2324  if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2325  LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2326  "expansion\n");
2327 
2328  // Get the stack frame index of a 8 byte buffer.
2329  SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2330 
2331  // word offset constant for Hi/Lo address computation
2332  SDValue WordOff = DAG.getConstant(sizeof(int), dl,
2333  StackSlot.getValueType());
2334  // set up Hi and Lo (into buffer) address based on endian
2335  SDValue Hi = StackSlot;
2336  SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2337  StackSlot, WordOff);
2338  if (DAG.getDataLayout().isLittleEndian())
2339  std::swap(Hi, Lo);
2340 
2341  // if signed map to unsigned space
2342  SDValue Op0Mapped;
2343  if (isSigned) {
2344  // constant used to invert sign bit (signed to unsigned mapping)
2345  SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32);
2346  Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2347  } else {
2348  Op0Mapped = Op0;
2349  }
2350  // store the lo of the constructed double - based on integer input
2351  SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op0Mapped, Lo,
2352  MachinePointerInfo());
2353  // initial hi portion of constructed double
2354  SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2355  // store the hi of the constructed double - biased exponent
2356  SDValue Store2 =
2357  DAG.getStore(Store1, dl, InitialHi, Hi, MachinePointerInfo());
2358  // load the constructed double
2359  SDValue Load =
2360  DAG.getLoad(MVT::f64, dl, Store2, StackSlot, MachinePointerInfo());
2361  // FP constant to bias correct the final result
2362  SDValue Bias = DAG.getConstantFP(isSigned ?
2363  BitsToDouble(0x4330000080000000ULL) :
2364  BitsToDouble(0x4330000000000000ULL),
2365  dl, MVT::f64);
2366  // subtract the bias
2367  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2368  // final result
2369  SDValue Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2370  return Result;
2371  }
2372  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2373  // Code below here assumes !isSigned without checking again.
2374 
2375  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2376 
2377  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2378  DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2379  SDValue Zero = DAG.getIntPtrConstant(0, dl),
2380  Four = DAG.getIntPtrConstant(4, dl);
2381  SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2382  SignSet, Four, Zero);
2383 
2384  // If the sign bit of the integer is set, the large number will be treated
2385  // as a negative number. To counteract this, the dynamic code adds an
2386  // offset depending on the data type.
2387  uint64_t FF;
2388  switch (SrcVT.getSimpleVT().SimpleTy) {
2389  default: llvm_unreachable("Unsupported integer type!");
2390  case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2391  case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2392  case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2393  case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2394  }
2395  if (DAG.getDataLayout().isLittleEndian())
2396  FF <<= 32;
2397  Constant *FudgeFactor = ConstantInt::get(
2398  Type::getInt64Ty(*DAG.getContext()), FF);
2399 
2400  SDValue CPIdx =
2401  DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2402  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2403  CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2404  Alignment = std::min(Alignment, 4u);
2405  SDValue FudgeInReg;
2406  if (DestVT == MVT::f32)
2407  FudgeInReg = DAG.getLoad(
2408  MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2409  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2410  Alignment);
2411  else {
2412  SDValue Load = DAG.getExtLoad(
2413  ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2414  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2415  Alignment);
2416  HandleSDNode Handle(Load);
2417  LegalizeOp(Load.getNode());
2418  FudgeInReg = Handle.getValue();
2419  }
2420 
2421  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2422 }
2423 
2424 /// This function is responsible for legalizing a
2425 /// *INT_TO_FP operation of the specified operand when the target requests that
2426 /// we promote it. At this point, we know that the result and operand types are
2427 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2428 /// operation that takes a larger input.
2429 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT,
2430  bool isSigned,
2431  const SDLoc &dl) {
2432  // First step, figure out the appropriate *INT_TO_FP operation to use.
2433  EVT NewInTy = LegalOp.getValueType();
2434 
2435  unsigned OpToUse = 0;
2436 
2437  // Scan for the appropriate larger type to use.
2438  while (true) {
2439  NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2440  assert(NewInTy.isInteger() && "Ran out of possibilities!");
2441 
2442  // If the target supports SINT_TO_FP of this type, use it.
2443  if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2444  OpToUse = ISD::SINT_TO_FP;
2445  break;
2446  }
2447  if (isSigned) continue;
2448 
2449  // If the target supports UINT_TO_FP of this type, use it.
2450  if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2451  OpToUse = ISD::UINT_TO_FP;
2452  break;
2453  }
2454 
2455  // Otherwise, try a larger type.
2456  }
2457 
2458  // Okay, we found the operation and type to use. Zero extend our input to the
2459  // desired type then run the operation on it.
2460  return DAG.getNode(OpToUse, dl, DestVT,
2461  DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2462  dl, NewInTy, LegalOp));
2463 }
2464 
2465 /// This function is responsible for legalizing a
2466 /// FP_TO_*INT operation of the specified operand when the target requests that
2467 /// we promote it. At this point, we know that the result and operand types are
2468 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2469 /// operation that returns a larger result.
2470 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT,
2471  bool isSigned,
2472  const SDLoc &dl) {
2473  // First step, figure out the appropriate FP_TO*INT operation to use.
2474  EVT NewOutTy = DestVT;
2475 
2476  unsigned OpToUse = 0;
2477 
2478  // Scan for the appropriate larger type to use.
2479  while (true) {
2480  NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2481  assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2482 
2483  // A larger signed type can hold all unsigned values of the requested type,
2484  // so using FP_TO_SINT is valid
2485  if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2486  OpToUse = ISD::FP_TO_SINT;
2487  break;
2488  }
2489 
2490  // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2491  if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2492  OpToUse = ISD::FP_TO_UINT;
2493  break;
2494  }
2495 
2496  // Otherwise, try a larger type.
2497  }
2498 
2499  // Okay, we found the operation and type to use.
2500  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2501 
2502  // Truncate the result of the extended FP_TO_*INT operation to the desired
2503  // size.
2504  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2505 }
2506 
2507 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts.
2508 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) {
2509  EVT VT = Op.getValueType();
2510  EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2511  unsigned Sz = VT.getScalarSizeInBits();
2512 
2513  SDValue Tmp, Tmp2, Tmp3;
2514 
2515  // If we can, perform BSWAP first and then the mask+swap the i4, then i2
2516  // and finally the i1 pairs.
2517  // TODO: We can easily support i4/i2 legal types if any target ever does.
2518  if (Sz >= 8 && isPowerOf2_32(Sz)) {
2519  // Create the masks - repeating the pattern every byte.
2520  APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0));
2521  APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC));
2522  APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA));
2523  APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F));
2524  APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33));
2525  APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55));
2526 
2527  // BSWAP if the type is wider than a single byte.
2528  Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
2529 
2530  // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4)
2531  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT));
2532  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT));
2533  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT));
2534  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
2535  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2536 
2537  // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2)
2538  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT));
2539  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT));
2540  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT));
2541  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
2542  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2543 
2544  // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1)
2545  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT));
2546  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT));
2547  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT));
2548  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
2549  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2550  return Tmp;
2551  }
2552 
2553  Tmp = DAG.getConstant(0, dl, VT);
2554  for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
2555  if (I < J)
2556  Tmp2 =
2557  DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
2558  else
2559  Tmp2 =
2560  DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
2561 
2562  APInt Shift(Sz, 1);
2563  Shift <<= J;
2564  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
2565  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
2566  }
2567 
2568  return Tmp;
2569 }
2570 
2571 /// Open code the operations for BSWAP of the specified operation.
2572 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) {
2573  EVT VT = Op.getValueType();
2574  EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2575  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2576  switch (VT.getSimpleVT().getScalarType().SimpleTy) {
2577  default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2578  case MVT::i16:
2579  // Use a rotate by 8. This can be further expanded if necessary.
2580  return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2581  case MVT::i32:
2582  Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2583  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2584  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2585  Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2586  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2587  DAG.getConstant(0xFF0000, dl, VT));
2588  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
2589  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2590  Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2591  return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2592  case MVT::i64:
2593  Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2594  Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2595  Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2596  Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2597  Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2598  Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2599  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2600  Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2601  Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
2602  DAG.getConstant(255ULL<<48, dl, VT));
2603  Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
2604  DAG.getConstant(255ULL<<40, dl, VT));
2605  Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
2606  DAG.getConstant(255ULL<<32, dl, VT));
2607  Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
2608  DAG.getConstant(255ULL<<24, dl, VT));
2609  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2610  DAG.getConstant(255ULL<<16, dl, VT));
2611  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
2612  DAG.getConstant(255ULL<<8 , dl, VT));
2613  Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2614  Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2615  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2616  Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2617  Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2618  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2619  return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2620  }
2621 }
2622 
2623 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2624  LLVM_DEBUG(dbgs() << "Trying to expand node\n");
2626  SDLoc dl(Node);
2627  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2628  bool NeedInvert;
2629  switch (Node->getOpcode()) {
2630  case ISD::ABS:
2631  if (TLI.expandABS(Node, Tmp1, DAG))
2632  Results.push_back(Tmp1);
2633  break;
2634  case ISD::CTPOP:
2635  if (TLI.expandCTPOP(Node, Tmp1, DAG))
2636  Results.push_back(Tmp1);
2637  break;
2638  case ISD::CTLZ:
2639  case ISD::CTLZ_ZERO_UNDEF:
2640  if (TLI.expandCTLZ(Node, Tmp1, DAG))
2641  Results.push_back(Tmp1);
2642  break;
2643  case ISD::CTTZ:
2644  case ISD::CTTZ_ZERO_UNDEF:
2645  if (TLI.expandCTTZ(Node, Tmp1, DAG))
2646  Results.push_back(Tmp1);
2647  break;
2648  case ISD::BITREVERSE:
2649  Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl));
2650  break;
2651  case ISD::BSWAP:
2652  Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2653  break;
2654  case ISD::FRAMEADDR:
2655  case ISD::RETURNADDR:
2657  Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2658  break;
2659  case ISD::EH_DWARF_CFA: {
2660  SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
2661  TLI.getPointerTy(DAG.getDataLayout()));
2662  SDValue Offset = DAG.getNode(ISD::ADD, dl,
2663  CfaArg.getValueType(),
2664  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
2665  CfaArg.getValueType()),
2666  CfaArg);
2667  SDValue FA = DAG.getNode(
2668  ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()),
2669  DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
2670  Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
2671  FA, Offset));
2672  break;
2673  }
2674  case ISD::FLT_ROUNDS_:
2675  Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2676  break;
2677  case ISD::EH_RETURN:
2678  case ISD::EH_LABEL:
2679  case ISD::PREFETCH:
2680  case ISD::VAEND:
2681  case ISD::EH_SJLJ_LONGJMP:
2682  // If the target didn't expand these, there's nothing to do, so just
2683  // preserve the chain and be done.
2684  Results.push_back(Node->getOperand(0));
2685  break;
2686  case ISD::READCYCLECOUNTER:
2687  // If the target didn't expand this, just return 'zero' and preserve the
2688  // chain.
2689  Results.append(Node->getNumValues() - 1,
2690  DAG.getConstant(0, dl, Node->getValueType(0)));
2691  Results.push_back(Node->getOperand(0));
2692  break;
2693  case ISD::EH_SJLJ_SETJMP:
2694  // If the target didn't expand this, just return 'zero' and preserve the
2695  // chain.
2696  Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2697  Results.push_back(Node->getOperand(0));
2698  break;
2699  case ISD::ATOMIC_LOAD: {
2700  // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2701  SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2702  SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2703  SDValue Swap = DAG.getAtomicCmpSwap(
2704  ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2705  Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2706  cast<AtomicSDNode>(Node)->getMemOperand());
2707  Results.push_back(Swap.getValue(0));
2708  Results.push_back(Swap.getValue(1));
2709  break;
2710  }
2711  case ISD::ATOMIC_STORE: {
2712  // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2713  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2714  cast<AtomicSDNode>(Node)->getMemoryVT(),
2715  Node->getOperand(0),
2716  Node->getOperand(1), Node->getOperand(2),
2717  cast<AtomicSDNode>(Node)->getMemOperand());
2718  Results.push_back(Swap.getValue(1));
2719  break;
2720  }
2722  // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
2723  // splits out the success value as a comparison. Expanding the resulting
2724  // ATOMIC_CMP_SWAP will produce a libcall.
2725  SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2726  SDValue Res = DAG.getAtomicCmpSwap(
2727  ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2728  Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
2729  Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
2730 
2731  SDValue ExtRes = Res;
2732  SDValue LHS = Res;
2733  SDValue RHS = Node->getOperand(1);
2734 
2735  EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2736  EVT OuterType = Node->getValueType(0);
2737  switch (TLI.getExtendForAtomicOps()) {
2738  case ISD::SIGN_EXTEND:
2739  LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2740  DAG.getValueType(AtomicType));
2741  RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2742  Node->getOperand(2), DAG.getValueType(AtomicType));
2743  ExtRes = LHS;
2744  break;
2745  case ISD::ZERO_EXTEND:
2746  LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2747  DAG.getValueType(AtomicType));
2748  RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2749  ExtRes = LHS;
2750  break;
2751  case ISD::ANY_EXTEND:
2752  LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2753  RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2754  break;
2755  default:
2756  llvm_unreachable("Invalid atomic op extension");
2757  }
2758 
2759  SDValue Success =
2760  DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2761 
2762  Results.push_back(ExtRes.getValue(0));
2763  Results.push_back(Success);
2764  Results.push_back(Res.getValue(1));
2765  break;
2766  }
2768  ExpandDYNAMIC_STACKALLOC(Node, Results);
2769  break;
2770  case ISD::MERGE_VALUES:
2771  for (unsigned i = 0; i < Node->getNumValues(); i++)
2772  Results.push_back(Node->getOperand(i));
2773  break;
2774  case ISD::UNDEF: {
2775  EVT VT = Node->getValueType(0);
2776  if (VT.isInteger())
2777  Results.push_back(DAG.getConstant(0, dl, VT));
2778  else {
2779  assert(VT.isFloatingPoint() && "Unknown value type!");
2780  Results.push_back(DAG.getConstantFP(0, dl, VT));
2781  }
2782  break;
2783  }
2784  case ISD::STRICT_FP_ROUND:
2785  // This expansion does not honor the "strict" properties anyway,
2786  // so prefer falling back to the non-strict operation if legal.
2787  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2788  Node->getValueType(0))
2790  break;
2791  Tmp1 = EmitStackConvert(Node->getOperand(1),
2792  Node->getValueType(0),
2793  Node->getValueType(0), dl, Node->getOperand(0));
2794  ReplaceNode(Node, Tmp1.getNode());
2795  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
2796  return true;
2797  case ISD::FP_ROUND:
2798  case ISD::BITCAST:
2799  Tmp1 = EmitStackConvert(Node->getOperand(0),
2800  Node->getValueType(0),
2801  Node->getValueType(0), dl);
2802  Results.push_back(Tmp1);
2803  break;
2804  case ISD::STRICT_FP_EXTEND:
2805  // This expansion does not honor the "strict" properties anyway,
2806  // so prefer falling back to the non-strict operation if legal.
2807  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2808  Node->getValueType(0))
2810  break;
2811  Tmp1 = EmitStackConvert(Node->getOperand(1),
2812  Node->getOperand(1).getValueType(),
2813  Node->getValueType(0), dl, Node->getOperand(0));
2814  ReplaceNode(Node, Tmp1.getNode());
2815  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
2816  return true;
2817  case ISD::FP_EXTEND:
2818  Tmp1 = EmitStackConvert(Node->getOperand(0),
2819  Node->getOperand(0).getValueType(),
2820  Node->getValueType(0), dl);
2821  Results.push_back(Tmp1);
2822  break;
2823  case ISD::SIGN_EXTEND_INREG: {
2824  EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2825  EVT VT = Node->getValueType(0);
2826 
2827  // An in-register sign-extend of a boolean is a negation:
2828  // 'true' (1) sign-extended is -1.
2829  // 'false' (0) sign-extended is 0.
2830  // However, we must mask the high bits of the source operand because the
2831  // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
2832 
2833  // TODO: Do this for vectors too?
2834  if (ExtraVT.getSizeInBits() == 1) {
2835  SDValue One = DAG.getConstant(1, dl, VT);
2836  SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
2837  SDValue Zero = DAG.getConstant(0, dl, VT);
2838  SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
2839  Results.push_back(Neg);
2840  break;
2841  }
2842 
2843  // NOTE: we could fall back on load/store here too for targets without
2844  // SRA. However, it is doubtful that any exist.
2845  EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2846  unsigned BitsDiff = VT.getScalarSizeInBits() -
2847  ExtraVT.getScalarSizeInBits();
2848  SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
2849  Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2850  Node->getOperand(0), ShiftCst);
2851  Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2852  Results.push_back(Tmp1);
2853  break;
2854  }
2855  case ISD::FP_ROUND_INREG: {
2856  // The only way we can lower this is to turn it into a TRUNCSTORE,
2857  // EXTLOAD pair, targeting a temporary location (a stack slot).
2858 
2859  // NOTE: there is a choice here between constantly creating new stack
2860  // slots and always reusing the same one. We currently always create
2861  // new ones, as reuse may inhibit scheduling.
2862  EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2863  Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2864  Node->getValueType(0), dl);
2865  Results.push_back(Tmp1);
2866  break;
2867  }
2868  case ISD::UINT_TO_FP:
2869  if (TLI.expandUINT_TO_FP(Node, Tmp1, DAG)) {
2870  Results.push_back(Tmp1);
2871  break;
2872  }
2874  case ISD::SINT_TO_FP:
2875  Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2876  Node->getOperand(0), Node->getValueType(0), dl);
2877  Results.push_back(Tmp1);
2878  break;
2879  case ISD::FP_TO_SINT:
2880  if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
2881  Results.push_back(Tmp1);
2882  break;
2883  case ISD::FP_TO_UINT:
2884  if (TLI.expandFP_TO_UINT(Node, Tmp1, DAG))
2885  Results.push_back(Tmp1);
2886  break;
2887  case ISD::LROUND:
2888  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
2889  RTLIB::LROUND_F64, RTLIB::LROUND_F80,
2890  RTLIB::LROUND_F128,
2891  RTLIB::LROUND_PPCF128));
2892  break;
2893  case ISD::LLROUND:
2894  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
2895  RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
2896  RTLIB::LLROUND_F128,
2897  RTLIB::LLROUND_PPCF128));
2898  break;
2899  case ISD::LRINT:
2900  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
2901  RTLIB::LRINT_F64, RTLIB::LRINT_F80,
2902  RTLIB::LRINT_F128,
2903  RTLIB::LRINT_PPCF128));
2904  break;
2905  case ISD::LLRINT:
2906  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
2907  RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
2908  RTLIB::LLRINT_F128,
2909  RTLIB::LLRINT_PPCF128));
2910  break;
2911  case ISD::VAARG:
2912  Results.push_back(DAG.expandVAArg(Node));
2913  Results.push_back(Results[0].getValue(1));
2914  break;
2915  case ISD::VACOPY:
2916  Results.push_back(DAG.expandVACopy(Node));
2917  break;
2919  if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2920  // This must be an access of the only element. Return it.
2921  Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2922  Node->getOperand(0));
2923  else
2924  Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2925  Results.push_back(Tmp1);
2926  break;
2928  Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2929  break;
2930  case ISD::INSERT_SUBVECTOR:
2931  Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
2932  break;
2933  case ISD::CONCAT_VECTORS:
2934  Results.push_back(ExpandVectorBuildThroughStack(Node));
2935  break;
2936  case ISD::SCALAR_TO_VECTOR:
2937  Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2938  break;
2940  Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2941  Node->getOperand(1),
2942  Node->getOperand(2), dl));
2943  break;
2944  case ISD::VECTOR_SHUFFLE: {
2945  SmallVector<int, 32> NewMask;
2946  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
2947 
2948  EVT VT = Node->getValueType(0);
2949  EVT EltVT = VT.getVectorElementType();
2950  SDValue Op0 = Node->getOperand(0);
2951  SDValue Op1 = Node->getOperand(1);
2952  if (!TLI.isTypeLegal(EltVT)) {
2953  EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2954 
2955  // BUILD_VECTOR operands are allowed to be wider than the element type.
2956  // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
2957  // it.
2958  if (NewEltVT.bitsLT(EltVT)) {
2959  // Convert shuffle node.
2960  // If original node was v4i64 and the new EltVT is i32,
2961  // cast operands to v8i32 and re-build the mask.
2962 
2963  // Calculate new VT, the size of the new VT should be equal to original.
2964  EVT NewVT =
2965  EVT::getVectorVT(*DAG.getContext(), NewEltVT,
2966  VT.getSizeInBits() / NewEltVT.getSizeInBits());
2967  assert(NewVT.bitsEq(VT));
2968 
2969  // cast operands to new VT
2970  Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
2971  Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
2972 
2973  // Convert the shuffle mask
2974  unsigned int factor =
2976 
2977  // EltVT gets smaller
2978  assert(factor > 0);
2979 
2980  for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
2981  if (Mask[i] < 0) {
2982  for (unsigned fi = 0; fi < factor; ++fi)
2983  NewMask.push_back(Mask[i]);
2984  }
2985  else {
2986  for (unsigned fi = 0; fi < factor; ++fi)
2987  NewMask.push_back(Mask[i]*factor+fi);
2988  }
2989  }
2990  Mask = NewMask;
2991  VT = NewVT;
2992  }
2993  EltVT = NewEltVT;
2994  }
2995  unsigned NumElems = VT.getVectorNumElements();
2997  for (unsigned i = 0; i != NumElems; ++i) {
2998  if (Mask[i] < 0) {
2999  Ops.push_back(DAG.getUNDEF(EltVT));
3000  continue;
3001  }
3002  unsigned Idx = Mask[i];
3003  if (Idx < NumElems)
3004  Ops.push_back(DAG.getNode(
3005  ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3006  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3007  else
3008  Ops.push_back(DAG.getNode(
3009  ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3010  DAG.getConstant(Idx - NumElems, dl,
3011  TLI.getVectorIdxTy(DAG.getDataLayout()))));
3012  }
3013 
3014  Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3015  // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3016  Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3017  Results.push_back(Tmp1);
3018  break;
3019  }
3020  case ISD::EXTRACT_ELEMENT: {
3021  EVT OpTy = Node->getOperand(0).getValueType();
3022  if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3023  // 1 -> Hi
3024  Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3025  DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3026  TLI.getShiftAmountTy(
3027  Node->getOperand(0).getValueType(),
3028  DAG.getDataLayout())));
3029  Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3030  } else {
3031  // 0 -> Lo
3032  Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3033  Node->getOperand(0));
3034  }
3035  Results.push_back(Tmp1);
3036  break;
3037  }
3038  case ISD::STACKSAVE:
3039  // Expand to CopyFromReg if the target set
3040  // StackPointerRegisterToSaveRestore.
3041  if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3042  Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3043  Node->getValueType(0)));
3044  Results.push_back(Results[0].getValue(1));
3045  } else {
3046  Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3047  Results.push_back(Node->getOperand(0));
3048  }
3049  break;
3050  case ISD::STACKRESTORE:
3051  // Expand to CopyToReg if the target set
3052  // StackPointerRegisterToSaveRestore.
3053  if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3054  Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3055  Node->getOperand(1)));
3056  } else {
3057  Results.push_back(Node->getOperand(0));
3058  }
3059  break;
3061  Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3062  Results.push_back(Results[0].getValue(0));
3063  break;
3064  case ISD::FCOPYSIGN:
3065  Results.push_back(ExpandFCOPYSIGN(Node));
3066  break;
3067  case ISD::FNEG:
3068  // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3069  Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3070  // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3071  Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3072  Node->getOperand(0));
3073  Results.push_back(Tmp1);
3074  break;
3075  case ISD::FABS:
3076  Results.push_back(ExpandFABS(Node));
3077  break;
3078  case ISD::SMIN:
3079  case ISD::SMAX:
3080  case ISD::UMIN:
3081  case ISD::UMAX: {
3082  // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3083  ISD::CondCode Pred;
3084  switch (Node->getOpcode()) {
3085  default: llvm_unreachable("How did we get here?");
3086  case ISD::SMAX: Pred = ISD::SETGT; break;
3087  case ISD::SMIN: Pred = ISD::SETLT; break;
3088  case ISD::UMAX: Pred = ISD::SETUGT; break;
3089  case ISD::UMIN: Pred = ISD::SETULT; break;
3090  }
3091  Tmp1 = Node->getOperand(0);
3092  Tmp2 = Node->getOperand(1);
3093  Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3094  Results.push_back(Tmp1);
3095  break;
3096  }
3097  case ISD::FMINNUM:
3098  case ISD::FMAXNUM: {
3099  if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3100  Results.push_back(Expanded);
3101  break;
3102  }
3103  case ISD::FSIN:
3104  case ISD::FCOS: {
3105  EVT VT = Node->getValueType(0);
3106  // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3107  // fcos which share the same operand and both are used.
3108  if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3109  isSinCosLibcallAvailable(Node, TLI))
3110  && useSinCos(Node)) {
3111  SDVTList VTs = DAG.getVTList(VT, VT);
3112  Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3113  if (Node->getOpcode() == ISD::FCOS)
3114  Tmp1 = Tmp1.getValue(1);
3115  Results.push_back(Tmp1);
3116  }
3117  break;
3118  }
3119  case ISD::FMAD:
3120  llvm_unreachable("Illegal fmad should never be formed");
3121 
3122  case ISD::FP16_TO_FP:
3123  if (Node->getValueType(0) != MVT::f32) {
3124  // We can extend to types bigger than f32 in two steps without changing
3125  // the result. Since "f16 -> f32" is much more commonly available, give
3126  // CodeGen the option of emitting that before resorting to a libcall.
3127  SDValue Res =
3128  DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3129  Results.push_back(
3130  DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3131  }
3132  break;
3133  case ISD::FP_TO_FP16:
3134  LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
3135  if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3136  SDValue Op = Node->getOperand(0);
3137  MVT SVT = Op.getSimpleValueType();
3138  if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3139  TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3140  // Under fastmath, we can expand this node into a fround followed by
3141  // a float-half conversion.
3142  SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3143  DAG.getIntPtrConstant(0, dl));
3144  Results.push_back(
3145  DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3146  }
3147  }
3148  break;
3149  case ISD::ConstantFP: {
3150  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3151  // Check to see if this FP immediate is already legal.
3152  // If this is a legal constant, turn it into a TargetConstantFP node.
3153  if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
3154  DAG.getMachineFunction().getFunction().hasOptSize()))
3155  Results.push_back(ExpandConstantFP(CFP, true));
3156  break;
3157  }
3158  case ISD::Constant: {
3159  ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3160  Results.push_back(ExpandConstant(CP));
3161  break;
3162  }
3163  case ISD::FSUB: {
3164  EVT VT = Node->getValueType(0);
3165  if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3166  TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3167  const SDNodeFlags Flags = Node->getFlags();
3168  Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3169  Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3170  Results.push_back(Tmp1);
3171  }
3172  break;
3173  }
3174  case ISD::SUB: {
3175  EVT VT = Node->getValueType(0);
3176  assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3177  TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3178  "Don't know how to expand this subtraction!");
3179  Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3180  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3181  VT));
3182  Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3183  Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3184  break;
3185  }
3186  case ISD::UREM:
3187  case ISD::SREM: {
3188  EVT VT = Node->getValueType(0);
3189  bool isSigned = Node->getOpcode() == ISD::SREM;
3190  unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3191  unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3192  Tmp2 = Node->getOperand(0);
3193  Tmp3 = Node->getOperand(1);
3194  if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3195  SDVTList VTs = DAG.getVTList(VT, VT);
3196  Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3197  Results.push_back(Tmp1);
3198  } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3199  // X % Y -> X-X/Y*Y
3200  Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3201  Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3202  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3203  Results.push_back(Tmp1);
3204  }
3205  break;
3206  }
3207  case ISD::UDIV:
3208  case ISD::SDIV: {
3209  bool isSigned = Node->getOpcode() == ISD::SDIV;
3210  unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3211  EVT VT = Node->getValueType(0);
3212  if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3213  SDVTList VTs = DAG.getVTList(VT, VT);
3214  Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3215  Node->getOperand(1));
3216  Results.push_back(Tmp1);
3217  }
3218  break;
3219  }
3220  case ISD::MULHU:
3221  case ISD::MULHS: {
3222  unsigned ExpandOpcode =
3224  EVT VT = Node->getValueType(0);
3225  SDVTList VTs = DAG.getVTList(VT, VT);
3226 
3227  Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3228  Node->getOperand(1));
3229  Results.push_back(Tmp1.getValue(1));
3230  break;
3231  }
3232  case ISD::UMUL_LOHI:
3233  case ISD::SMUL_LOHI: {
3234  SDValue LHS = Node->getOperand(0);
3235  SDValue RHS = Node->getOperand(1);
3236  MVT VT = LHS.getSimpleValueType();
3237  unsigned MULHOpcode =
3239 
3240  if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
3241  Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
3242  Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
3243  break;
3244  }
3245 
3246  SmallVector<SDValue, 4> Halves;
3247  EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
3248  assert(TLI.isTypeLegal(HalfType));
3249  if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves,
3250  HalfType, DAG,
3252  for (unsigned i = 0; i < 2; ++i) {
3253  SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
3254  SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
3255  SDValue Shift = DAG.getConstant(
3256  HalfType.getScalarSizeInBits(), dl,
3257  TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3258  Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3259  Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3260  }
3261  break;
3262  }
3263  break;
3264  }
3265  case ISD::MUL: {
3266  EVT VT = Node->getValueType(0);
3267  SDVTList VTs = DAG.getVTList(VT, VT);
3268  // See if multiply or divide can be lowered using two-result operations.
3269  // We just need the low half of the multiply; try both the signed
3270  // and unsigned forms. If the target supports both SMUL_LOHI and
3271  // UMUL_LOHI, form a preference by checking which forms of plain
3272  // MULH it supports.
3273  bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3274  bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3275  bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3276  bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3277  unsigned OpToUse = 0;
3278  if (HasSMUL_LOHI && !HasMULHS) {
3279  OpToUse = ISD::SMUL_LOHI;
3280  } else if (HasUMUL_LOHI && !HasMULHU) {
3281  OpToUse = ISD::UMUL_LOHI;
3282  } else if (HasSMUL_LOHI) {
3283  OpToUse = ISD::SMUL_LOHI;
3284  } else if (HasUMUL_LOHI) {
3285  OpToUse = ISD::UMUL_LOHI;
3286  }
3287  if (OpToUse) {
3288  Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3289  Node->getOperand(1)));
3290  break;
3291  }
3292 
3293  SDValue Lo, Hi;
3294  EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3295  if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3296  TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3297  TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3298  TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3299  TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
3301  Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3302  Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3303  SDValue Shift =
3304  DAG.getConstant(HalfType.getSizeInBits(), dl,
3305  TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3306  Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3307  Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3308  }
3309  break;
3310  }
3311  case ISD::FSHL:
3312  case ISD::FSHR:
3313  if (TLI.expandFunnelShift(Node, Tmp1, DAG))
3314  Results.push_back(Tmp1);
3315  break;
3316  case ISD::ROTL:
3317  case ISD::ROTR:
3318  if (TLI.expandROT(Node, Tmp1, DAG))
3319  Results.push_back(Tmp1);
3320  break;
3321  case ISD::SADDSAT:
3322  case ISD::UADDSAT:
3323  case ISD::SSUBSAT:
3324  case ISD::USUBSAT:
3325  Results.push_back(TLI.expandAddSubSat(Node, DAG));
3326  break;
3327  case ISD::SMULFIX:
3328  case ISD::SMULFIXSAT:
3329  case ISD::UMULFIX:
3330  Results.push_back(TLI.expandFixedPointMul(Node, DAG));
3331  break;
3332  case ISD::ADDCARRY:
3333  case ISD::SUBCARRY: {
3334  SDValue LHS = Node->getOperand(0);
3335  SDValue RHS = Node->getOperand(1);
3336  SDValue Carry = Node->getOperand(2);
3337 
3338  bool IsAdd = Node->getOpcode() == ISD::ADDCARRY;
3339 
3340  // Initial add of the 2 operands.
3341  unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
3342  EVT VT = LHS.getValueType();
3343  SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
3344 
3345  // Initial check for overflow.
3346  EVT CarryType = Node->getValueType(1);
3347  EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3348  ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
3349  SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3350 
3351  // Add of the sum and the carry.
3352  SDValue CarryExt =
3353  DAG.getZeroExtendInReg(DAG.getZExtOrTrunc(Carry, dl, VT), dl, MVT::i1);
3354  SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
3355 
3356  // Second check for overflow. If we are adding, we can only overflow if the
3357  // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
3358  // If we are subtracting, we can only overflow if the initial sum is 0 and
3359  // the carry is set, resulting in a new sum of all 1s.
3360  SDValue Zero = DAG.getConstant(0, dl, VT);
3361  SDValue Overflow2 =
3362  IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
3363  : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
3364  Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
3365  DAG.getZExtOrTrunc(Carry, dl, SetCCType));
3366 
3367  SDValue ResultCarry =
3368  DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
3369 
3370  Results.push_back(Sum2);
3371  Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
3372  break;
3373  }
3374  case ISD::SADDO:
3375  case ISD::SSUBO: {
3376  SDValue Result, Overflow;
3377  TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
3378  Results.push_back(Result);
3379  Results.push_back(Overflow);
3380  break;
3381  }
3382  case ISD::UADDO:
3383  case ISD::USUBO: {
3384  SDValue Result, Overflow;
3385  TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
3386  Results.push_back(Result);
3387  Results.push_back(Overflow);
3388  break;
3389  }
3390  case ISD::UMULO:
3391  case ISD::SMULO: {
3392  SDValue Result, Overflow;
3393  if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
3394  Results.push_back(Result);
3395  Results.push_back(Overflow);
3396  }
3397  break;
3398  }
3399  case ISD::BUILD_PAIR: {
3400  EVT PairTy = Node->getValueType(0);
3401  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3402  Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3403  Tmp2 = DAG.getNode(
3404  ISD::SHL, dl, PairTy, Tmp2,
3405  DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3406  TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3407  Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3408  break;
3409  }
3410  case ISD::SELECT:
3411  Tmp1 = Node->getOperand(0);
3412  Tmp2 = Node->getOperand(1);
3413  Tmp3 = Node->getOperand(2);
3414  if (Tmp1.getOpcode() == ISD::SETCC) {
3415  Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3416  Tmp2, Tmp3,
3417  cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3418  } else {
3419  Tmp1 = DAG.getSelectCC(dl, Tmp1,
3420  DAG.getConstant(0, dl, Tmp1.getValueType()),
3421  Tmp2, Tmp3, ISD::SETNE);
3422  }
3423  Tmp1->setFlags(Node->getFlags());
3424  Results.push_back(Tmp1);
3425  break;
3426  case ISD::BR_JT: {
3427  SDValue Chain = Node->getOperand(0);
3428  SDValue Table = Node->getOperand(1);
3429  SDValue Index = Node->getOperand(2);
3430 
3431  const DataLayout &TD = DAG.getDataLayout();
3432  EVT PTy = TLI.getPointerTy(TD);
3433 
3434  unsigned EntrySize =
3435  DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3436 
3437  // For power-of-two jumptable entry sizes convert multiplication to a shift.
3438  // This transformation needs to be done here since otherwise the MIPS
3439  // backend will end up emitting a three instruction multiply sequence
3440  // instead of a single shift and MSP430 will call a runtime function.
3441  if (llvm::isPowerOf2_32(EntrySize))
3442  Index = DAG.getNode(
3443  ISD::SHL, dl, Index.getValueType(), Index,
3444  DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
3445  else
3446  Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3447  DAG.getConstant(EntrySize, dl, Index.getValueType()));
3448  SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3449  Index, Table);
3450 
3451  EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3452  SDValue LD = DAG.getExtLoad(
3453  ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3454  MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
3455  Addr = LD;
3456  if (TLI.isJumpTableRelative()) {
3457  // For PIC, the sequence is:
3458  // BRIND(load(Jumptable + index) + RelocBase)
3459  // RelocBase can be JumpTable, GOT or some sort of global base.
3460  Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3461  TLI.getPICJumpTableRelocBase(Table, DAG));
3462  }
3463 
3464  Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG);
3465  Results.push_back(Tmp1);
3466  break;
3467  }
3468  case ISD::BRCOND:
3469  // Expand brcond's setcc into its constituent parts and create a BR_CC
3470  // Node.
3471  Tmp1 = Node->getOperand(0);
3472  Tmp2 = Node->getOperand(1);
3473  if (Tmp2.getOpcode() == ISD::SETCC) {
3474  Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3475  Tmp1, Tmp2.getOperand(2),
3476  Tmp2.getOperand(0), Tmp2.getOperand(1),
3477  Node->getOperand(2));
3478  } else {
3479  // We test only the i1 bit. Skip the AND if UNDEF or another AND.
3480  if (Tmp2.isUndef() ||
3481  (Tmp2.getOpcode() == ISD::AND &&
3482  isa<ConstantSDNode>(Tmp2.getOperand(1)) &&
3483  cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1))
3484  Tmp3 = Tmp2;
3485  else
3486  Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3487  DAG.getConstant(1, dl, Tmp2.getValueType()));
3488  Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3489  DAG.getCondCode(ISD::SETNE), Tmp3,
3490  DAG.getConstant(0, dl, Tmp3.getValueType()),
3491  Node->getOperand(2));
3492  }
3493  Results.push_back(Tmp1);
3494  break;
3495  case ISD::SETCC: {
3496  Tmp1 = Node->getOperand(0);
3497  Tmp2 = Node->getOperand(1);
3498  Tmp3 = Node->getOperand(2);
3499  bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3500  Tmp3, NeedInvert, dl);
3501 
3502  if (Legalized) {
3503  // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3504  // condition code, create a new SETCC node.
3505  if (Tmp3.getNode())
3506  Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3507  Tmp1, Tmp2, Tmp3, Node->getFlags());
3508 
3509  // If we expanded the SETCC by inverting the condition code, then wrap
3510  // the existing SETCC in a NOT to restore the intended condition.
3511  if (NeedInvert)
3512  Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3513 
3514  Results.push_back(Tmp1);
3515  break;
3516  }
3517 
3518  // Otherwise, SETCC for the given comparison type must be completely
3519  // illegal; expand it into a SELECT_CC.
3520  EVT VT = Node->getValueType(0);
3521  int TrueValue;
3522  switch (TLI.getBooleanContents(Tmp1.getValueType())) {
3525  TrueValue = 1;
3526  break;
3528  TrueValue = -1;
3529  break;
3530  }
3531  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3532  DAG.getConstant(TrueValue, dl, VT),
3533  DAG.getConstant(0, dl, VT),
3534  Tmp3);
3535  Tmp1->setFlags(Node->getFlags());
3536  Results.push_back(Tmp1);
3537  break;
3538  }
3539  case ISD::SELECT_CC: {
3540  Tmp1 = Node->getOperand(0); // LHS
3541  Tmp2 = Node->getOperand(1); // RHS
3542  Tmp3 = Node->getOperand(2); // True
3543  Tmp4 = Node->getOperand(3); // False
3544  EVT VT = Node->getValueType(0);
3545  SDValue CC = Node->getOperand(4);
3546  ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3547 
3548  if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
3549  // If the condition code is legal, then we need to expand this
3550  // node using SETCC and SELECT.
3551  EVT CmpVT = Tmp1.getValueType();
3552  assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3553  "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3554  "expanded.");
3555  EVT CCVT = getSetCCResultType(CmpVT);
3556  SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
3557  Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3558  break;
3559  }
3560 
3561  // SELECT_CC is legal, so the condition code must not be.
3562  bool Legalized = false;
3563  // Try to legalize by inverting the condition. This is for targets that
3564  // might support an ordered version of a condition, but not the unordered
3565  // version (or vice versa).
3566  ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3567  Tmp1.getValueType().isInteger());
3568  if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
3569  // Use the new condition code and swap true and false
3570  Legalized = true;
3571  Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3572  Tmp1->setFlags(Node->getFlags());
3573  } else {
3574  // If The inverse is not legal, then try to swap the arguments using
3575  // the inverse condition code.
3576  ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3577  if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
3578  // The swapped inverse condition is legal, so swap true and false,
3579  // lhs and rhs.
3580  Legalized = true;
3581  Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3582  Tmp1->setFlags(Node->getFlags());
3583  }
3584  }
3585 
3586  if (!Legalized) {
3587  Legalized = LegalizeSetCCCondCode(
3588  getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3589  dl);
3590 
3591  assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3592 
3593  // If we expanded the SETCC by inverting the condition code, then swap
3594  // the True/False operands to match.
3595  if (NeedInvert)
3596  std::swap(Tmp3, Tmp4);
3597 
3598  // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3599  // condition code, create a new SELECT_CC node.
3600  if (CC.getNode()) {
3601  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3602  Tmp1, Tmp2, Tmp3, Tmp4, CC);
3603  } else {
3604  Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3605  CC = DAG.getCondCode(ISD::SETNE);
3606  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3607  Tmp2, Tmp3, Tmp4, CC);
3608  }
3609  Tmp1->setFlags(Node->getFlags());
3610  }
3611  Results.push_back(Tmp1);
3612  break;
3613  }
3614  case ISD::BR_CC: {
3615  Tmp1 = Node->getOperand(0); // Chain
3616  Tmp2 = Node->getOperand(2); // LHS
3617  Tmp3 = Node->getOperand(3); // RHS
3618  Tmp4 = Node->getOperand(1); // CC
3619 
3620  bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
3621  Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
3622  (void)Legalized;
3623  assert(Legalized && "Can't legalize BR_CC with legal condition!");
3624 
3625  assert(!NeedInvert && "Don't know how to invert BR_CC!");
3626 
3627  // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3628  // node.
3629  if (Tmp4.getNode()) {
3630  Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3631  Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3632  } else {
3633  Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3634  Tmp4 = DAG.getCondCode(ISD::SETNE);
3635  Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3636  Tmp2, Tmp3, Node->getOperand(4));
3637  }
3638  Results.push_back(Tmp1);
3639  break;
3640  }
3641  case ISD::BUILD_VECTOR:
3642  Results.push_back(ExpandBUILD_VECTOR(Node));
3643  break;
3644  case ISD::SRA:
3645  case ISD::SRL:
3646  case ISD::SHL: {
3647  // Scalarize vector SRA/SRL/SHL.
3648  EVT VT = Node->getValueType(0);
3649  assert(VT.isVector() && "Unable to legalize non-vector shift");
3650  assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3651  unsigned NumElem = VT.getVectorNumElements();
3652 
3653  SmallVector<SDValue, 8> Scalars;
3654  for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3655  SDValue Ex = DAG.getNode(
3656  ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
3657  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3658  SDValue Sh = DAG.getNode(
3659  ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
3660  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3661  Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3662  VT.getScalarType(), Ex, Sh));
3663  }
3664 
3665  SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
3666  ReplaceNode(SDValue(Node, 0), Result);
3667  break;
3668  }
3669  case ISD::VECREDUCE_FADD:
3670  case ISD::VECREDUCE_FMUL:
3671  case ISD::VECREDUCE_ADD:
3672  case ISD::VECREDUCE_MUL:
3673  case ISD::VECREDUCE_AND:
3674  case ISD::VECREDUCE_OR:
3675  case ISD::VECREDUCE_XOR:
3676  case ISD::VECREDUCE_SMAX:
3677  case ISD::VECREDUCE_SMIN:
3678  case ISD::VECREDUCE_UMAX:
3679  case ISD::VECREDUCE_UMIN:
3680  case ISD::VECREDUCE_FMAX:
3681  case ISD::VECREDUCE_FMIN:
3682  Results.push_back(TLI.expandVecReduce(Node, DAG));
3683  break;
3685  case ISD::GlobalAddress:
3686  case ISD::GlobalTLSAddress:
3687  case ISD::ExternalSymbol:
3688  case ISD::ConstantPool:
3689  case ISD::JumpTable:
3692  case ISD::INTRINSIC_VOID:
3693  // FIXME: Custom lowering for these operations shouldn't return null!
3694  break;
3695  }
3696 
3697  if (Results.empty() && Node->isStrictFPOpcode()) {
3698  // FIXME: We were asked to expand a strict floating-point operation,
3699  // but there is currently no expansion implemented that would preserve
3700  // the "strict" properties. For now, we just fall back to the non-strict
3701  // version if that is legal on the target. The actual mutation of the
3702  // operation will happen in SelectionDAGISel::DoInstructionSelection.
3703  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3704  Node->getValueType(0))
3706  return true;
3707  }
3708 
3709  // Replace the original node with the legalized result.
3710  if (Results.empty()) {
3711  LLVM_DEBUG(dbgs() << "Cannot expand node\n");
3712  return false;
3713  }
3714 
3715  LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
3716  ReplaceNode(Node, Results.data());
3717  return true;
3718 }
3719 
3720 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3721  LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
3723  SDLoc dl(Node);
3724  // FIXME: Check flags on the node to see if we can use a finite call.
3725  bool CanUseFiniteLibCall = TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath;
3726  unsigned Opc = Node->getOpcode();
3727  switch (Opc) {
3728  case ISD::ATOMIC_FENCE: {
3729  // If the target didn't lower this, lower it to '__sync_synchronize()' call
3730  // FIXME: handle "fence singlethread" more efficiently.
3732 
3734  CLI.setDebugLoc(dl)
3735  .setChain(Node->getOperand(0))
3736  .setLibCallee(
3737  CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3738  DAG.getExternalSymbol("__sync_synchronize",
3739  TLI.getPointerTy(DAG.getDataLayout())),
3740  std::move(Args));
3741 
3742  std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3743 
3744  Results.push_back(CallResult.second);
3745  break;
3746  }
3747  // By default, atomic intrinsics are marked Legal and lowered. Targets
3748  // which don't support them directly, however, may want libcalls, in which
3749  // case they mark them Expand, and we get here.
3750  case ISD::ATOMIC_SWAP:
3751  case ISD::ATOMIC_LOAD_ADD:
3752  case ISD::ATOMIC_LOAD_SUB:
3753  case ISD::ATOMIC_LOAD_AND:
3754  case ISD::ATOMIC_LOAD_CLR:
3755  case ISD::ATOMIC_LOAD_OR:
3756  case ISD::ATOMIC_LOAD_XOR:
3757  case ISD::ATOMIC_LOAD_NAND:
3758  case ISD::ATOMIC_LOAD_MIN:
3759  case ISD::ATOMIC_LOAD_MAX:
3760  case ISD::ATOMIC_LOAD_UMIN:
3761  case ISD::ATOMIC_LOAD_UMAX:
3762  case ISD::ATOMIC_CMP_SWAP: {
3763  MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3764  RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
3765  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
3766 
3767  std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false);
3768  Results.push_back(Tmp.first);
3769  Results.push_back(Tmp.second);
3770  break;
3771  }
3772  case ISD::TRAP: {
3773  // If this operation is not supported, lower it to 'abort()' call
3776  CLI.setDebugLoc(dl)
3777  .setChain(Node->getOperand(0))
3778  .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3779  DAG.getExternalSymbol(
3780  "abort", TLI.getPointerTy(DAG.getDataLayout())),
3781  std::move(Args));
3782  std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3783 
3784  Results.push_back(CallResult.second);
3785  break;
3786  }
3787  case ISD::FMINNUM:
3788  case ISD::STRICT_FMINNUM:
3789  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3790  RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3791  RTLIB::FMIN_PPCF128));
3792  break;
3793  case ISD::FMAXNUM:
3794  case ISD::STRICT_FMAXNUM:
3795  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
3796  RTLIB::FMAX_F80, RTLIB::FMAX_F128,
3797  RTLIB::FMAX_PPCF128));
3798  break;
3799  case ISD::FSQRT:
3800  case ISD::STRICT_FSQRT:
3801  Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3802  RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3803  RTLIB::SQRT_PPCF128));
3804  break;
3805  case ISD::FCBRT:
3806  Results.push_back(ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64,
3807  RTLIB::CBRT_F80, RTLIB::CBRT_F128,
3808  RTLIB::CBRT_PPCF128));
3809  break;
3810  case ISD::FSIN:
3811  case ISD::STRICT_FSIN:
3812  Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3813  RTLIB::SIN_F80, RTLIB::SIN_F128,
3814  RTLIB::SIN_PPCF128));
3815  break;
3816  case ISD::FCOS:
3817  case ISD::STRICT_FCOS:
3818  Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3819  RTLIB::COS_F80, RTLIB::COS_F128,
3820  RTLIB::COS_PPCF128));
3821  break;
3822  case ISD::FSINCOS:
3823  // Expand into sincos libcall.
3824  ExpandSinCosLibCall(Node, Results);
3825  break;
3826  case ISD::FLOG:
3827  case ISD::STRICT_FLOG:
3828  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log_finite))
3829  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_FINITE_F32,
3830  RTLIB::LOG_FINITE_F64,
3831  RTLIB::LOG_FINITE_F80,
3832  RTLIB::LOG_FINITE_F128,
3833  RTLIB::LOG_FINITE_PPCF128));
3834  else
3835  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3836  RTLIB::LOG_F80, RTLIB::LOG_F128,
3837  RTLIB::LOG_PPCF128));
3838  break;
3839  case ISD::FLOG2:
3840  case ISD::STRICT_FLOG2:
3841  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log2_finite))
3842  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_FINITE_F32,
3843  RTLIB::LOG2_FINITE_F64,
3844  RTLIB::LOG2_FINITE_F80,
3845  RTLIB::LOG2_FINITE_F128,
3846  RTLIB::LOG2_FINITE_PPCF128));
3847  else
3848  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3849  RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3850  RTLIB::LOG2_PPCF128));
3851  break;
3852  case ISD::FLOG10:
3853  case ISD::STRICT_FLOG10:
3854  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log10_finite))
3855  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_FINITE_F32,
3856  RTLIB::LOG10_FINITE_F64,
3857  RTLIB::LOG10_FINITE_F80,
3858  RTLIB::LOG10_FINITE_F128,
3859  RTLIB::LOG10_FINITE_PPCF128));
3860  else
3861  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3862  RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3863  RTLIB::LOG10_PPCF128));
3864  break;
3865  case ISD::FEXP:
3866  case ISD::STRICT_FEXP:
3867  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp_finite))
3868  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_FINITE_F32,
3869  RTLIB::EXP_FINITE_F64,
3870  RTLIB::EXP_FINITE_F80,
3871  RTLIB::EXP_FINITE_F128,
3872  RTLIB::EXP_FINITE_PPCF128));
3873  else
3874  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3875  RTLIB::EXP_F80, RTLIB::EXP_F128,
3876  RTLIB::EXP_PPCF128));
3877  break;
3878  case ISD::FEXP2:
3879  case ISD::STRICT_FEXP2:
3880  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp2_finite))
3881  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_FINITE_F32,
3882  RTLIB::EXP2_FINITE_F64,
3883  RTLIB::EXP2_FINITE_F80,
3884  RTLIB::EXP2_FINITE_F128,
3885  RTLIB::EXP2_FINITE_PPCF128));
3886  else
3887  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3888  RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3889  RTLIB::EXP2_PPCF128));
3890  break;
3891  case ISD::FTRUNC:
3892  case ISD::STRICT_FTRUNC:
3893  Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3894  RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3895  RTLIB::TRUNC_PPCF128));
3896  break;
3897  case ISD::FFLOOR:
3898  case ISD::STRICT_FFLOOR:
3899  Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3900  RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3901  RTLIB::FLOOR_PPCF128));
3902  break;
3903  case ISD::FCEIL:
3904  case ISD::STRICT_FCEIL:
3905  Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3906  RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3907  RTLIB::CEIL_PPCF128));
3908  break;
3909  case ISD::FRINT:
3910  case ISD::STRICT_FRINT:
3911  Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3912  RTLIB::RINT_F80, RTLIB::RINT_F128,
3913  RTLIB::RINT_PPCF128));
3914  break;
3915  case ISD::FNEARBYINT:
3917  Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3918  RTLIB::NEARBYINT_F64,
3919  RTLIB::NEARBYINT_F80,
3920  RTLIB::NEARBYINT_F128,
3921  RTLIB::NEARBYINT_PPCF128));
3922  break;
3923  case ISD::FROUND:
3924  case ISD::STRICT_FROUND:
3925  Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3926  RTLIB::ROUND_F64,
3927  RTLIB::ROUND_F80,
3928  RTLIB::ROUND_F128,
3929  RTLIB::ROUND_PPCF128));
3930  break;
3931  case ISD::FPOWI:
3932  case ISD::STRICT_FPOWI:
3933  Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3934  RTLIB::POWI_F80, RTLIB::POWI_F128,
3935  RTLIB::POWI_PPCF128));
3936  break;
3937  case ISD::FPOW:
3938  case ISD::STRICT_FPOW:
3939  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_pow_finite))
3940  Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_FINITE_F32,
3941  RTLIB::POW_FINITE_F64,
3942  RTLIB::POW_FINITE_F80,
3943  RTLIB::POW_FINITE_F128,
3944  RTLIB::POW_FINITE_PPCF128));
3945  else
3946  Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3947  RTLIB::POW_F80, RTLIB::POW_F128,
3948  RTLIB::POW_PPCF128));
3949  break;
3950  case ISD::FDIV:
3951  Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3952  RTLIB::DIV_F80, RTLIB::DIV_F128,
3953  RTLIB::DIV_PPCF128));
3954  break;
3955  case ISD::FREM:
3956  case ISD::STRICT_FREM:
3957  Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3958  RTLIB::REM_F80, RTLIB::REM_F128,
3959  RTLIB::REM_PPCF128));
3960  break;
3961  case ISD::FMA:
3962  case ISD::STRICT_FMA:
3963  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3964  RTLIB::FMA_F80, RTLIB::FMA_F128,
3965  RTLIB::FMA_PPCF128));
3966  break;
3967  case ISD::FADD:
3968  Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
3969  RTLIB::ADD_F80, RTLIB::ADD_F128,
3970  RTLIB::ADD_PPCF128));
3971  break;
3972  case ISD::FMUL:
3973  Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
3974  RTLIB::MUL_F80, RTLIB::MUL_F128,
3975  RTLIB::MUL_PPCF128));
3976  break;
3977  case ISD::FP16_TO_FP:
3978  if (Node->getValueType(0) == MVT::f32) {
3979  Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3980  }
3981  break;
3982  case ISD::FP_TO_FP16: {
3983  RTLIB::Libcall LC =
3985  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
3986  Results.push_back(ExpandLibCall(LC, Node, false));
3987  break;
3988  }
3989  case ISD::FSUB:
3990  Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
3991  RTLIB::SUB_F80, RTLIB::SUB_F128,
3992  RTLIB::SUB_PPCF128));
3993  break;
3994  case ISD::SREM:
3995  Results.push_back(ExpandIntLibCall(Node, true,
3996  RTLIB::SREM_I8,
3997  RTLIB::SREM_I16, RTLIB::SREM_I32,
3998  RTLIB::SREM_I64, RTLIB::SREM_I128));
3999  break;
4000  case ISD::UREM:
4001  Results.push_back(ExpandIntLibCall(Node, false,
4002  RTLIB::UREM_I8,
4003  RTLIB::UREM_I16, RTLIB::UREM_I32,
4004  RTLIB::UREM_I64, RTLIB::UREM_I128));
4005  break;
4006  case ISD::SDIV:
4007  Results.push_back(ExpandIntLibCall(Node, true,
4008  RTLIB::SDIV_I8,
4009  RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4010  RTLIB::SDIV_I64, RTLIB::SDIV_I128));
4011  break;
4012  case ISD::UDIV:
4013  Results.push_back(ExpandIntLibCall(Node, false,
4014  RTLIB::UDIV_I8,
4015  RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4016  RTLIB::UDIV_I64, RTLIB::UDIV_I128));
4017  break;
4018  case ISD::SDIVREM:
4019  case ISD::UDIVREM:
4020  // Expand into divrem libcall
4021  ExpandDivRemLibCall(Node, Results);
4022  break;
4023  case ISD::MUL:
4024  Results.push_back(ExpandIntLibCall(Node, false,
4025  RTLIB::MUL_I8,
4026  RTLIB::MUL_I16, RTLIB::MUL_I32,
4027  RTLIB::MUL_I64, RTLIB::MUL_I128));
4028  break;
4029  case ISD::CTLZ_ZERO_UNDEF:
4030  switch (Node->getSimpleValueType(0).SimpleTy) {
4031  default:
4032  llvm_unreachable("LibCall explicitly requested, but not available");
4033  case MVT::i32:
4034  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false));
4035  break;
4036  case MVT::i64:
4037  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false));
4038  break;
4039  case MVT::i128:
4040  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false));
4041  break;
4042  }
4043  break;
4044  }
4045 
4046  // Replace the original node with the legalized result.
4047  if (!Results.empty()) {
4048  LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
4049  ReplaceNode(Node, Results.data());
4050  } else
4051  LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
4052 }
4053 
4054 // Determine the vector type to use in place of an original scalar element when
4055 // promoting equally sized vectors.
4057  MVT EltVT, MVT NewEltVT) {
4058  unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4059  MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4060  assert(TLI.isTypeLegal(MidVT) && "unexpected");
4061  return MidVT;
4062 }
4063 
4064 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4065  LLVM_DEBUG(dbgs() << "Trying to promote node\n");
4067  MVT OVT = Node->getSimpleValueType(0);
4068  if (Node->getOpcode() == ISD::UINT_TO_FP ||
4069  Node->getOpcode() == ISD::SINT_TO_FP ||
4070  Node->getOpcode() == ISD::SETCC ||
4071  Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4072  Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4073  OVT = Node->getOperand(0).getSimpleValueType();
4074  }
4075  if (Node->getOpcode() == ISD::BR_CC)
4076  OVT = Node->getOperand(2).getSimpleValueType();
4077  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4078  SDLoc dl(Node);
4079  SDValue Tmp1, Tmp2, Tmp3;
4080  switch (Node->getOpcode()) {
4081  case ISD::CTTZ:
4082  case ISD::CTTZ_ZERO_UNDEF:
4083  case ISD::CTLZ:
4084  case ISD::CTLZ_ZERO_UNDEF:
4085  case ISD::CTPOP:
4086  // Zero extend the argument.
4087  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4088  if (Node->getOpcode() == ISD::CTTZ) {
4089  // The count is the same in the promoted type except if the original
4090  // value was zero. This can be handled by setting the bit just off
4091  // the top of the original type.
4092  auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4093  OVT.getSizeInBits());
4094  Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4095  DAG.getConstant(TopBit, dl, NVT));
4096  }
4097  // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4098  // already the correct result.
4099  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4100  if (Node->getOpcode() == ISD::CTLZ ||
4101  Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4102  // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4103  Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4104  DAG.getConstant(NVT.getSizeInBits() -
4105  OVT.getSizeInBits(), dl, NVT));
4106  }
4107  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4108  break;
4109  case ISD::BITREVERSE:
4110  case ISD::BSWAP: {
4111  unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4112  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4113  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4114  Tmp1 = DAG.getNode(
4115  ISD::SRL, dl, NVT, Tmp1,
4116  DAG.getConstant(DiffBits, dl,
4117  TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4118 
4119  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4120  break;
4121  }
4122  case ISD::FP_TO_UINT:
4123  case ISD::FP_TO_SINT:
4124  Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4125  Node->getOpcode() == ISD::FP_TO_SINT, dl);
4126  Results.push_back(Tmp1);
4127  break;
4128  case ISD::UINT_TO_FP:
4129  case ISD::SINT_TO_FP:
4130  Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4131  Node->getOpcode() == ISD::SINT_TO_FP, dl);
4132  Results.push_back(Tmp1);
4133  break;
4134  case ISD::VAARG: {
4135  SDValue Chain = Node->getOperand(0); // Get the chain.
4136  SDValue Ptr = Node->getOperand(1); // Get the pointer.
4137 
4138  unsigned TruncOp;
4139  if (OVT.isVector()) {
4140  TruncOp = ISD::BITCAST;
4141  } else {
4142  assert(OVT.isInteger()
4143  && "VAARG promotion is supported only for vectors or integer types");
4144  TruncOp = ISD::TRUNCATE;
4145  }
4146 
4147  // Perform the larger operation, then convert back
4148  Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4149  Node->getConstantOperandVal(3));
4150  Chain = Tmp1.getValue(1);
4151 
4152  Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4153 
4154  // Modified the chain result - switch anything that used the old chain to
4155  // use the new one.
4156  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4157  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4158  if (UpdatedNodes) {
4159  UpdatedNodes->insert(Tmp2.getNode());
4160  UpdatedNodes->insert(Chain.getNode());
4161  }
4162  ReplacedNode(Node);
4163  break;
4164  }
4165  case ISD::MUL:
4166  case ISD::SDIV:
4167  case ISD::SREM:
4168  case ISD::UDIV:
4169  case ISD::UREM:
4170  case ISD::AND:
4171  case ISD::OR:
4172  case ISD::XOR: {
4173  unsigned ExtOp, TruncOp;
4174  if (OVT.isVector()) {
4175  ExtOp = ISD::BITCAST;
4176  TruncOp = ISD::BITCAST;
4177  } else {
4178  assert(OVT.isInteger() && "Cannot promote logic operation");
4179 
4180  switch (Node->getOpcode()) {
4181  default:
4182  ExtOp = ISD::ANY_EXTEND;
4183  break;
4184  case ISD::SDIV:
4185  case ISD::SREM:
4186  ExtOp = ISD::SIGN_EXTEND;
4187  break;
4188  case ISD::UDIV:
4189  case ISD::UREM:
4190  ExtOp = ISD::ZERO_EXTEND;
4191  break;
4192  }
4193  TruncOp = ISD::TRUNCATE;
4194  }
4195  // Promote each of the values to the new type.
4196  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4197  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4198  // Perform the larger operation, then convert back
4199  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4200  Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4201  break;
4202  }
4203  case ISD::UMUL_LOHI:
4204  case ISD::SMUL_LOHI: {
4205  // Promote to a multiply in a wider integer type.
4206  unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
4207  : ISD::SIGN_EXTEND;
4208  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4209  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4210  Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
4211 
4212  auto &DL = DAG.getDataLayout();
4213  unsigned OriginalSize = OVT.getScalarSizeInBits();
4214  Tmp2 = DAG.getNode(
4215  ISD::SRL, dl, NVT, Tmp1,
4216  DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
4217  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4218  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
4219  break;
4220  }
4221  case ISD::SELECT: {
4222  unsigned ExtOp, TruncOp;
4223  if (Node->getValueType(0).isVector() ||
4224  Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4225  ExtOp = ISD::BITCAST;
4226  TruncOp = ISD::BITCAST;
4227  } else if (Node->getValueType(0).isInteger()) {
4228  ExtOp = ISD::ANY_EXTEND;
4229  TruncOp = ISD::TRUNCATE;
4230  } else {
4231  ExtOp = ISD::FP_EXTEND;
4232  TruncOp = ISD::FP_ROUND;
4233  }
4234  Tmp1 = Node->getOperand(0);
4235  // Promote each of the values to the new type.
4236  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4237  Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4238  // Perform the larger operation, then round down.
4239  Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4240  Tmp1->setFlags(Node->getFlags());
4241  if (TruncOp != ISD::FP_ROUND)
4242  Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4243  else
4244  Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4245  DAG.getIntPtrConstant(0, dl));
4246  Results.push_back(Tmp1);
4247  break;
4248  }
4249  case ISD::VECTOR_SHUFFLE: {
4250  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4251 
4252  // Cast the two input vectors.
4253  Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4254  Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4255 
4256  // Convert the shuffle mask to the right # elements.
4257  Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4258  Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4259  Results.push_back(Tmp1);
4260  break;
4261  }
4262  case ISD::SETCC: {
4263  unsigned ExtOp = ISD::FP_EXTEND;
4264  if (NVT.isInteger()) {
4265  ISD::CondCode CCCode =
4266  cast<CondCodeSDNode>(Node->getOperand(2))->get();
4268  }
4269  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4270  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4271  Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
4272  Tmp2, Node->getOperand(2), Node->getFlags()));
4273  break;
4274  }
4275  case ISD::BR_CC: {
4276  unsigned ExtOp = ISD::FP_EXTEND;
4277  if (NVT.isInteger()) {
4278  ISD::CondCode CCCode =
4279  cast<CondCodeSDNode>(Node->getOperand(1))->get();
4281  }
4282  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4283  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4284  Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4285  Node->getOperand(0), Node->getOperand(1),
4286  Tmp1, Tmp2, Node->getOperand(4)));
4287  break;
4288  }
4289  case ISD::FADD:
4290  case ISD::FSUB:
4291  case ISD::FMUL:
4292  case ISD::FDIV:
4293  case ISD::FREM:
4294  case ISD::FMINNUM:
4295  case ISD::FMAXNUM:
4296  case ISD::FPOW:
4297  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4298  Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4299  Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4300  Node->getFlags());
4301  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4302  Tmp3, DAG.getIntPtrConstant(0, dl)));
4303  break;
4304  case ISD::FMA:
4305  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4306  Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4307  Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4308  Results.push_back(
4309  DAG.getNode(ISD::FP_ROUND, dl, OVT,
4310  DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4311  DAG.getIntPtrConstant(0, dl)));
4312  break;
4313  case ISD::FCOPYSIGN:
4314  case ISD::FPOWI: {
4315  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4316  Tmp2 = Node->getOperand(1);
4317  Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4318 
4319  // fcopysign doesn't change anything but the sign bit, so
4320  // (fp_round (fcopysign (fpext a), b))
4321  // is as precise as
4322  // (fp_round (fpext a))
4323  // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4324  const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4325  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4326  Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4327  break;
4328  }
4329  case ISD::FFLOOR:
4330  case ISD::FCEIL:
4331  case ISD::FRINT:
4332  case ISD::FNEARBYINT:
4333  case ISD::FROUND:
4334  case ISD::FTRUNC:
4335  case ISD::FNEG:
4336  case ISD::FSQRT:
4337  case ISD::FSIN:
4338  case ISD::FCOS:
4339  case ISD::FLOG:
4340  case ISD::FLOG2:
4341  case ISD::FLOG10:
4342  case ISD::FABS:
4343  case ISD::FEXP:
4344  case ISD::FEXP2:
4345  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4346  Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4347  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4348  Tmp2, DAG.getIntPtrConstant(0, dl)));
4349  break;
4350  case ISD::BUILD_VECTOR: {
4351  MVT EltVT = OVT.getVectorElementType();
4352  MVT NewEltVT = NVT.getVectorElementType();
4353 
4354  // Handle bitcasts to a different vector type with the same total bit size
4355  //
4356  // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4357  // =>
4358  // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4359 
4360  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4361  "Invalid promote type for build_vector");
4362  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4363 
4364  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4365 
4366  SmallVector<SDValue, 8> NewOps;
4367  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4368  SDValue Op = Node->getOperand(I);
4369  NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4370  }
4371 
4372  SDLoc SL(Node);
4373  SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4374  SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4375  Results.push_back(CvtVec);
4376  break;
4377  }
4378  case ISD::EXTRACT_VECTOR_ELT: {
4379  MVT EltVT = OVT.getVectorElementType();
4380  MVT NewEltVT = NVT.getVectorElementType();
4381 
4382  // Handle bitcasts to a different vector type with the same total bit size.
4383  //
4384  // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4385  // =>
4386  // v4i32:castx = bitcast x:v2i64
4387  //
4388  // i64 = bitcast
4389  // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4390  // (i32 (extract_vector_elt castx, (2 * y + 1)))
4391  //
4392 
4393  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4394  "Invalid promote type for extract_vector_elt");
4395  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4396 
4397  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4398  unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4399 
4400  SDValue Idx = Node->getOperand(1);
4401  EVT IdxVT = Idx.getValueType();
4402  SDLoc SL(Node);
4403  SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4404  SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4405 
4406  SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4407 
4408  SmallVector<SDValue, 8> NewOps;
4409  for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4410  SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4411  SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4412 
4413  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4414  CastVec, TmpIdx);
4415  NewOps.push_back(Elt);
4416  }
4417 
4418  SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
4419  Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4420  break;
4421  }
4422  case ISD::INSERT_VECTOR_ELT: {
4423  MVT EltVT = OVT.getVectorElementType();
4424  MVT NewEltVT = NVT.getVectorElementType();
4425 
4426  // Handle bitcasts to a different vector type with the same total bit size
4427  //
4428  // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4429  // =>
4430  // v4i32:castx = bitcast x:v2i64
4431  // v2i32:casty = bitcast y:i64
4432  //
4433  // v2i64 = bitcast
4434  // (v4i32 insert_vector_elt
4435  // (v4i32 insert_vector_elt v4i32:castx,
4436  // (extract_vector_elt casty, 0), 2 * z),
4437  // (extract_vector_elt casty, 1), (2 * z + 1))
4438 
4439  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4440  "Invalid promote type for insert_vector_elt");
4441  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4442 
4443  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4444  unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4445 
4446  SDValue Val = Node->getOperand(1);
4447  SDValue Idx = Node->getOperand(2);
4448  EVT IdxVT = Idx.getValueType();
4449  SDLoc SL(Node);
4450 
4451  SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4452  SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4453 
4454  SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4455  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4456 
4457  SDValue NewVec = CastVec;
4458  for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4459  SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4460  SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4461 
4462  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4463  CastVal, IdxOffset);
4464 
4465  NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4466  NewVec, Elt, InEltIdx);
4467  }
4468 
4469  Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4470  break;
4471  }
4472  case ISD::SCALAR_TO_VECTOR: {
4473  MVT EltVT = OVT.getVectorElementType();
4474  MVT NewEltVT = NVT.getVectorElementType();
4475 
4476  // Handle bitcasts to different vector type with the same total bit size.
4477  //
4478  // e.g. v2i64 = scalar_to_vector x:i64
4479  // =>
4480  // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4481  //
4482 
4483  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4484  SDValue Val = Node->getOperand(0);
4485  SDLoc SL(Node);
4486 
4487  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4488  SDValue Undef = DAG.getUNDEF(MidVT);
4489 
4490  SmallVector<SDValue, 8> NewElts;
4491  NewElts.push_back(CastVal);
4492  for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4493  NewElts.push_back(Undef);
4494 
4495  SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4496  SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4497  Results.push_back(CvtVec);
4498  break;
4499  }
4500  case ISD::ATOMIC_SWAP: {
4501  AtomicSDNode *AM = cast<AtomicSDNode>(Node);
4502  SDLoc SL(Node);
4503  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
4504  assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
4505  "unexpected promotion type");
4506  assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
4507  "unexpected atomic_swap with illegal type");
4508 
4509  SDValue NewAtomic
4510  = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT,
4511  DAG.getVTList(NVT, MVT::Other),
4512  { AM->getChain(), AM->getBasePtr(), CastVal },
4513  AM->getMemOperand());
4514  Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
4515  Results.push_back(NewAtomic.getValue(1));
4516  break;
4517  }
4518  }
4519 
4520  // Replace the original node with the legalized result.
4521  if (!Results.empty()) {
4522  LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
4523  ReplaceNode(Node, Results.data());
4524  } else
4525  LLVM_DEBUG(dbgs() << "Could not promote node\n");
4526 }
4527 
4528 /// This is the entry point for the file.
4530  AssignTopologicalOrder();
4531 
4532  SmallPtrSet<SDNode *, 16> LegalizedNodes;
4533  // Use a delete listener to remove nodes which were deleted during
4534  // legalization from LegalizeNodes. This is needed to handle the situation
4535  // where a new node is allocated by the object pool to the same address of a
4536  // previously deleted node.
4537  DAGNodeDeletedListener DeleteListener(
4538  *this,
4539  [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
4540 
4541  SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4542 
4543  // Visit all the nodes. We start in topological order, so that we see
4544  // nodes with their original operands intact. Legalization can produce
4545  // new nodes which may themselves need to be legalized. Iterate until all
4546  // nodes have been legalized.
4547  while (true) {
4548  bool AnyLegalized = false;
4549  for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4550  --NI;
4551 
4552  SDNode *N = &*NI;
4553  if (N->use_empty() && N != getRoot().getNode()) {
4554  ++NI;
4555  DeleteNode(N);
4556  continue;
4557  }
4558 
4559  if (LegalizedNodes.insert(N).second) {
4560  AnyLegalized = true;
4561  Legalizer.LegalizeOp(N);
4562 
4563  if (N->use_empty() && N != getRoot().getNode()) {
4564  ++NI;
4565  DeleteNode(N);
4566  }
4567  }
4568  }
4569  if (!AnyLegalized)
4570  break;
4571 
4572  }
4573 
4574  // Remove dead nodes now.
4575  RemoveDeadNodes();
4576 }
4577 
4579  SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4580  SmallPtrSet<SDNode *, 16> LegalizedNodes;
4581  SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4582 
4583  // Directly insert the node in question, and legalize it. This will recurse
4584  // as needed through operands.
4585  LegalizedNodes.insert(N);
4586  Legalizer.LegalizeOp(N);
4587 
4588  return LegalizedNodes.count(N);
4589 }
bool LegalizeOp(SDNode *N, SmallSetVector< SDNode *, 16 > &UpdatedNodes)
Transforms a SelectionDAG node and any operands to it into a node that is compatible with the target ...
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
Definition: ISDOpcodes.h:795
static Constant * getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1697
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:595
X = FP_ROUND(Y, TRUNC) - Rounding &#39;Y&#39; from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:562
BUILTIN_OP_END - This must be the last enum value in this list.
Definition: ISDOpcodes.h:913
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:622
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isInteger() const
Return true if this is an integer or a vector integer type.
void setFlags(SDNodeFlags NewFlags)
static bool isConstant(const MachineInstr &MI)
bool isUndef() const
static MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.
Constrained versions of libm-equivalent floating point intrinsics.
Definition: ISDOpcodes.h:300
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant, which is required to be operand #1) half of the integer or float value specified as operand #0.
Definition: ISDOpcodes.h:183
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isIndexed() const
Return true if this is a pre/post inc/dec load/store.
NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR (an vector value) starting with the ...
Definition: ISDOpcodes.h:382
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BR_CC - Conditional branch.
Definition: ISDOpcodes.h:678
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static MVT getVectorVT(MVT VT, unsigned NumElements)
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition: ISDOpcodes.h:391
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition: ValueTypes.h:259
const SDValue & getVal() const
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition: ISDOpcodes.h:284
bool isVector() const
Return true if this is a vector value type.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
Libcall getSYNC(unsigned Opc, MVT VT)
Return the SYNC_FETCH_AND_* value for the given opcode and type, or UNKNOWN_LIBCALL if there is none...
const SDValue & getBasePtr() const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void push_back(const T &Elt)
Definition: SmallVector.h:211
const SDValue & getValue() const
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain...
Definition: ISDOpcodes.h:730
SDVTList getVTList() const
This file contains the declarations for metadata subclasses.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:252
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition: ISDOpcodes.h:250
const SDValue & getBasePtr() const
unsigned getVectorNumElements() const
const SDValue & getChain() const
Function Alias Analysis Results
static MVT getPromotedVectorElementType(const TargetLowering &TLI, MVT EltVT, MVT NewEltVT)
unsigned getAlignment() const
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
Definition: ISDOpcodes.h:833
unsigned second
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:813
static uint32_t Concat[]
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:140
F(f)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:408
const SDNodeFlags getFlags() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
Same for subtraction.
Definition: ISDOpcodes.h:253
void reserve(size_type N)
Definition: SmallVector.h:369
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition: ValueTypes.h:211
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1 at the ...
Definition: ISDOpcodes.h:377
The address of the GOT.
Definition: ISDOpcodes.h:65
unsigned getValueSizeInBits() const
Returns the size of the value in bits.
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
Definition: ISDOpcodes.h:812
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:459
std::pair< MCSymbol *, MachineModuleInfoImpl::StubValueTy > PairTy
Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none...
const ConstantFP * getConstantFPValue() const
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:158
bool isTruncatingStore() const
Return true if the op does a truncation before store.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode *> &Visited, SmallVectorImpl< const SDNode *> &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic...
Definition: ISDOpcodes.h:113
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition: ISDOpcodes.h:209
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:135
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations...
Definition: ISDOpcodes.h:480
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Shift and rotation operations.
Definition: ISDOpcodes.h:434
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:261
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth...
Definition: ISDOpcodes.h:417
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:654
CallLoweringInfo & setChain(SDValue InChain)
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition: ISDOpcodes.h:190
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition: ISDOpcodes.h:279
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
op_iterator op_end() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
FLT_ROUNDS_ - Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest 2 Round to ...
Definition: ISDOpcodes.h:570
SimpleValueType SimpleTy
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence, and carry arbitrary information that target might want to know.
Definition: ISDOpcodes.h:744
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA)...
Definition: ISDOpcodes.h:95
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amt) For double-word atomic operations: ValLo, ValHi, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amtLo, amtHi) ValLo, ValHi, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amtLo, amtHi) These correspond to the atomicrmw instruction.
Definition: ISDOpcodes.h:841
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:413
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG...
Definition: ISDOpcodes.h:72
This is an SDNode representing atomic operations.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
This file implements a class to represent arbitrary precision integral constant values and operations...
This represents a list of ValueType&#39;s that has been intern&#39;d by a SelectionDAG.
STACKSAVE - STACKSAVE has one operand, an input chain.
Definition: ISDOpcodes.h:726
FRAME_TO_ARGS_OFFSET - This node represents offset from frame pointer to first (possible) on-stack ar...
Definition: ISDOpcodes.h:90
unsigned getSizeInBits() const
unsigned getScalarSizeInBits() const
Definition: ValueTypes.h:297
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:291
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition: ISDOpcodes.h:502
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here...
Definition: ISDOpcodes.h:117
falkor hwpf fix Falkor HW Prefetch Fix Late Phase
const TargetMachine & getTarget() const
Definition: SelectionDAG.h:414
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
CallLoweringInfo & setZExtResult(bool Value=true)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
Definition: SelectionDAG.h:874
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:1012
op_iterator op_begin() const
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:323
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification, or lowering of the constant.
Definition: ISDOpcodes.h:124
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
Definition: ISDOpcodes.h:778
static bool useSinCos(SDNode *Node)
Only issue sincos libcall if both sin and cos are needed.
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
Definition: ISDOpcodes.h:1045
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition: ISDOpcodes.h:150
MVT getVectorElementType() const
UNDEF - An undefined node.
Definition: ISDOpcodes.h:177
This class is used to represent ISD::STORE nodes.
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition: ISDOpcodes.h:548
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a vector with the specified, possibly variable...
Definition: ISDOpcodes.h:351
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: