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