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