1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/Constants.h"
25 //===----------------------------------------------------------------------===//
26 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it. This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing. For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
38 class SelectionDAGLegalize {
42 /// LegalizeAction - This enum indicates what action we should take for each
43 /// value type the can occur in the program.
45 Legal, // The target natively supports this value type.
46 Promote, // This should be promoted to the next larger type.
47 Expand, // This integer type should be broken into smaller pieces.
50 /// TransformToType - For any value types we are promoting or expanding, this
51 /// contains the value type that we are changing to. For Expanded types, this
52 /// contains one step of the expand (e.g. i64 -> i32), even if there are
53 /// multiple steps required (e.g. i64 -> i16)
54 MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
56 /// ValueTypeActions - This is a bitvector that contains two bits for each
57 /// value type, where the two bits correspond to the LegalizeAction enum.
58 /// This can be queried with "getTypeAction(VT)".
59 unsigned ValueTypeActions;
61 /// NeedsAnotherIteration - This is set when we expand a large integer
62 /// operation into smaller integer operations, but the smaller operations are
63 /// not set. This occurs only rarely in practice, for targets that don't have
64 /// 32-bit or larger integer registers.
65 bool NeedsAnotherIteration;
67 /// LegalizedNodes - For nodes that are of legal width, and that have more
68 /// than one use, this map indicates what regularized operand to use. This
69 /// allows us to avoid legalizing the same thing more than once.
70 std::map<SDOperand, SDOperand> LegalizedNodes;
72 /// PromotedNodes - For nodes that are below legal width, and that have more
73 /// than one use, this map indicates what promoted value to use. This allows
74 /// us to avoid promoting the same thing more than once.
75 std::map<SDOperand, SDOperand> PromotedNodes;
77 /// ExpandedNodes - For nodes that need to be expanded, and which have more
78 /// than one use, this map indicates which which operands are the expanded
79 /// version of the input. This allows us to avoid expanding the same node
81 std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
83 void AddLegalizedOperand(SDOperand From, SDOperand To) {
84 bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
85 assert(isNew && "Got into the map somehow?");
87 void AddPromotedOperand(SDOperand From, SDOperand To) {
88 bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
89 assert(isNew && "Got into the map somehow?");
92 /// setValueTypeAction - Set the action for a particular value type. This
93 /// assumes an action has not already been set for this value type.
94 void setValueTypeAction(MVT::ValueType VT, LegalizeAction A) {
95 ValueTypeActions |= A << (VT*2);
97 MVT::ValueType PromoteTo;
101 unsigned LargerReg = VT+1;
102 while (!TLI.hasNativeSupportFor((MVT::ValueType)LargerReg)) {
104 assert(MVT::isInteger((MVT::ValueType)LargerReg) &&
105 "Nothing to promote to??");
107 PromoteTo = (MVT::ValueType)LargerReg;
110 assert(MVT::isInteger(VT) == MVT::isInteger(PromoteTo) &&
111 MVT::isFloatingPoint(VT) == MVT::isFloatingPoint(PromoteTo) &&
112 "Can only promote from int->int or fp->fp!");
113 assert(VT < PromoteTo && "Must promote to a larger type!");
114 TransformToType[VT] = PromoteTo;
115 } else if (A == Expand) {
116 assert(MVT::isInteger(VT) && VT > MVT::i8 &&
117 "Cannot expand this type: target must support SOME integer reg!");
118 // Expand to the next smaller integer type!
119 TransformToType[VT] = (MVT::ValueType)(VT-1);
125 SelectionDAGLegalize(TargetLowering &TLI, SelectionDAG &DAG);
127 /// Run - While there is still lowering to do, perform a pass over the DAG.
128 /// Most regularization can be done in a single pass, but targets that require
129 /// large values to be split into registers multiple times (e.g. i64 -> 4x
130 /// i16) require iteration for these values (the first iteration will demote
131 /// to i32, the second will demote to i16).
134 NeedsAnotherIteration = false;
136 } while (NeedsAnotherIteration);
139 /// getTypeAction - Return how we should legalize values of this type, either
140 /// it is already legal or we need to expand it into multiple registers of
141 /// smaller integer type, or we need to promote it to a larger type.
142 LegalizeAction getTypeAction(MVT::ValueType VT) const {
143 return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
146 /// isTypeLegal - Return true if this type is legal on this target.
148 bool isTypeLegal(MVT::ValueType VT) const {
149 return getTypeAction(VT) == Legal;
155 SDOperand LegalizeOp(SDOperand O);
156 void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157 SDOperand PromoteOp(SDOperand O);
159 SDOperand getIntPtrConstant(uint64_t Val) {
160 return DAG.getConstant(Val, TLI.getPointerTy());
166 SelectionDAGLegalize::SelectionDAGLegalize(TargetLowering &tli,
168 : TLI(tli), DAG(dag), ValueTypeActions(0) {
170 assert(MVT::LAST_VALUETYPE <= 16 &&
171 "Too many value types for ValueTypeActions to hold!");
173 // Inspect all of the ValueType's possible, deciding how to process them.
174 for (unsigned IntReg = MVT::i1; IntReg <= MVT::i128; ++IntReg)
175 // If TLI says we are expanding this type, expand it!
176 if (TLI.getNumElements((MVT::ValueType)IntReg) != 1)
177 setValueTypeAction((MVT::ValueType)IntReg, Expand);
178 else if (!TLI.hasNativeSupportFor((MVT::ValueType)IntReg))
179 // Otherwise, if we don't have native support, we must promote to a
181 setValueTypeAction((MVT::ValueType)IntReg, Promote);
183 // If the target does not have native support for F32, promote it to F64.
184 if (!TLI.hasNativeSupportFor(MVT::f32))
185 setValueTypeAction(MVT::f32, Promote);
188 void SelectionDAGLegalize::LegalizeDAG() {
189 SDOperand OldRoot = DAG.getRoot();
190 SDOperand NewRoot = LegalizeOp(OldRoot);
191 DAG.setRoot(NewRoot);
193 ExpandedNodes.clear();
194 LegalizedNodes.clear();
196 // Remove dead nodes now.
197 DAG.RemoveDeadNodes(OldRoot.Val);
200 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
201 assert(getTypeAction(Op.getValueType()) == Legal &&
202 "Caller should expand or promote operands that are not legal!");
204 // If this operation defines any values that cannot be represented in a
205 // register on this target, make sure to expand or promote them.
206 if (Op.Val->getNumValues() > 1) {
207 for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
208 switch (getTypeAction(Op.Val->getValueType(i))) {
209 case Legal: break; // Nothing to do.
212 ExpandOp(Op.getValue(i), T1, T2);
213 assert(LegalizedNodes.count(Op) &&
214 "Expansion didn't add legal operands!");
215 return LegalizedNodes[Op];
218 PromoteOp(Op.getValue(i));
219 assert(LegalizedNodes.count(Op) &&
220 "Expansion didn't add legal operands!");
221 return LegalizedNodes[Op];
225 std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
226 if (I != LegalizedNodes.end()) return I->second;
228 SDOperand Tmp1, Tmp2, Tmp3;
230 SDOperand Result = Op;
231 SDNode *Node = Op.Val;
233 switch (Node->getOpcode()) {
235 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
236 assert(0 && "Do not know how to legalize this operator!");
238 case ISD::EntryToken:
239 case ISD::FrameIndex:
240 case ISD::GlobalAddress:
241 case ISD::ExternalSymbol:
242 case ISD::ConstantPool: // Nothing to do.
243 assert(getTypeAction(Node->getValueType(0)) == Legal &&
244 "This must be legal!");
246 case ISD::CopyFromReg:
247 Tmp1 = LegalizeOp(Node->getOperand(0));
248 if (Tmp1 != Node->getOperand(0))
249 Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
250 Node->getValueType(0), Tmp1);
252 case ISD::ImplicitDef:
253 Tmp1 = LegalizeOp(Node->getOperand(0));
254 if (Tmp1 != Node->getOperand(0))
255 Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
258 // We know we don't need to expand constants here, constants only have one
259 // value and we check that it is fine above.
261 // FIXME: Maybe we should handle things like targets that don't support full
262 // 32-bit immediates?
264 case ISD::ConstantFP: {
265 // Spill FP immediates to the constant pool if the target cannot directly
266 // codegen them. Targets often have some immediate values that can be
267 // efficiently generated into an FP register without a load. We explicitly
268 // leave these constants as ConstantFP nodes for the target to deal with.
270 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
272 // Check to see if this FP immediate is already legal.
273 bool isLegal = false;
274 for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
275 E = TLI.legal_fpimm_end(); I != E; ++I)
276 if (CFP->isExactlyValue(*I)) {
282 // Otherwise we need to spill the constant to memory.
283 MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
287 // If a FP immediate is precise when represented as a float, we put it
288 // into the constant pool as a float, even if it's is statically typed
290 MVT::ValueType VT = CFP->getValueType(0);
291 bool isDouble = VT == MVT::f64;
292 ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
293 Type::FloatTy, CFP->getValue());
294 if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
295 LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
300 SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
302 Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
304 if (Extend) Result = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Result);
308 case ISD::TokenFactor: {
309 std::vector<SDOperand> Ops;
310 bool Changed = false;
311 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
312 Ops.push_back(LegalizeOp(Node->getOperand(i))); // Legalize the operands
313 Changed |= Ops[i] != Node->getOperand(i);
316 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
320 case ISD::ADJCALLSTACKDOWN:
321 case ISD::ADJCALLSTACKUP:
322 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
323 // There is no need to legalize the size argument (Operand #1)
324 if (Tmp1 != Node->getOperand(0))
325 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
326 Node->getOperand(1));
328 case ISD::DYNAMIC_STACKALLOC:
329 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
330 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the size.
331 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the alignment.
332 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
333 Tmp3 != Node->getOperand(2))
334 Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
337 Result = Op.getValue(0);
339 // Since this op produces two values, make sure to remember that we
340 // legalized both of them.
341 AddLegalizedOperand(SDOperand(Node, 0), Result);
342 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
343 return Result.getValue(Op.ResNo);
346 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
347 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
348 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
349 std::vector<MVT::ValueType> RetTyVTs;
350 RetTyVTs.reserve(Node->getNumValues());
351 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
352 RetTyVTs.push_back(Node->getValueType(i));
353 Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2), 0);
355 Result = Result.getValue(0);
357 // Since calls produce multiple values, make sure to remember that we
358 // legalized all of them.
359 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
360 AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
361 return Result.getValue(Op.ResNo);
364 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
365 if (Tmp1 != Node->getOperand(0))
366 Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
370 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
371 // FIXME: booleans might not be legal!
372 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
373 // Basic block destination (Op#2) is always legal.
374 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
375 Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
376 Node->getOperand(2));
380 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
381 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
382 if (Tmp1 != Node->getOperand(0) ||
383 Tmp2 != Node->getOperand(1))
384 Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
386 Result = SDOperand(Node, 0);
388 // Since loads produce two values, make sure to remember that we legalized
390 AddLegalizedOperand(SDOperand(Node, 0), Result);
391 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
392 return Result.getValue(Op.ResNo);
397 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
398 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
399 if (Tmp1 != Node->getOperand(0) ||
400 Tmp2 != Node->getOperand(1))
401 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
402 cast<MVTSDNode>(Node)->getExtraValueType());
404 Result = SDOperand(Node, 0);
406 // Since loads produce two values, make sure to remember that we legalized
408 AddLegalizedOperand(SDOperand(Node, 0), Result);
409 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
410 return Result.getValue(Op.ResNo);
412 case ISD::EXTRACT_ELEMENT:
413 // Get both the low and high parts.
414 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
415 if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
416 Result = Tmp2; // 1 -> Hi
418 Result = Tmp1; // 0 -> Lo
422 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
424 switch (getTypeAction(Node->getOperand(1).getValueType())) {
426 // Legalize the incoming value (must be legal).
427 Tmp2 = LegalizeOp(Node->getOperand(1));
428 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
429 Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
433 ExpandOp(Node->getOperand(1), Lo, Hi);
434 unsigned Reg = cast<RegSDNode>(Node)->getReg();
435 Result = DAG.getCopyToReg(Tmp1, Lo, Reg);
436 Result = DAG.getCopyToReg(Result, Hi, Reg+1);
437 assert(isTypeLegal(Result.getValueType()) &&
438 "Cannot expand multiple times yet (i64 -> i16)");
442 assert(0 && "Don't know what it means to promote this!");
448 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
449 switch (Node->getNumOperands()) {
451 switch (getTypeAction(Node->getOperand(1).getValueType())) {
453 Tmp2 = LegalizeOp(Node->getOperand(1));
454 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
455 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
459 ExpandOp(Node->getOperand(1), Lo, Hi);
460 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
464 assert(0 && "Can't promote return value!");
468 if (Tmp1 != Node->getOperand(0))
469 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
471 default: { // ret <values>
472 std::vector<SDOperand> NewValues;
473 NewValues.push_back(Tmp1);
474 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
475 switch (getTypeAction(Node->getOperand(i).getValueType())) {
477 NewValues.push_back(LegalizeOp(Node->getOperand(i)));
481 ExpandOp(Node->getOperand(i), Lo, Hi);
482 NewValues.push_back(Lo);
483 NewValues.push_back(Hi);
487 assert(0 && "Can't promote return value!");
489 Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
495 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
496 Tmp2 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
498 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
499 if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
500 if (CFP->getValueType(0) == MVT::f32) {
505 V.F = CFP->getValue();
506 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
507 DAG.getConstant(V.I, MVT::i32), Tmp2);
509 assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
514 V.F = CFP->getValue();
515 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
516 DAG.getConstant(V.I, MVT::i64), Tmp2);
522 switch (getTypeAction(Node->getOperand(1).getValueType())) {
524 SDOperand Val = LegalizeOp(Node->getOperand(1));
525 if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
526 Tmp2 != Node->getOperand(2))
527 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
531 // Truncate the value and store the result.
532 Tmp3 = PromoteOp(Node->getOperand(1));
533 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
534 Node->getOperand(1).getValueType());
539 ExpandOp(Node->getOperand(1), Lo, Hi);
541 if (!TLI.isLittleEndian())
544 // FIXME: These two stores are independent of each other!
545 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
547 unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
548 Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
549 getIntPtrConstant(IncrementSize));
550 assert(isTypeLegal(Tmp2.getValueType()) &&
551 "Pointers must be legal!");
552 Result = DAG.getNode(ISD::STORE, MVT::Other, Result, Hi, Tmp2);
555 case ISD::TRUNCSTORE:
556 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
557 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
559 switch (getTypeAction(Node->getOperand(1).getValueType())) {
561 Tmp2 = LegalizeOp(Node->getOperand(1));
562 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
563 Tmp3 != Node->getOperand(2))
564 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
565 cast<MVTSDNode>(Node)->getExtraValueType());
569 assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
573 // FIXME: BOOLS MAY REQUIRE PROMOTION!
574 Tmp1 = LegalizeOp(Node->getOperand(0)); // Cond
575 Tmp2 = LegalizeOp(Node->getOperand(1)); // TrueVal
576 Tmp3 = LegalizeOp(Node->getOperand(2)); // FalseVal
578 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
579 Tmp3 != Node->getOperand(2))
580 Result = DAG.getNode(ISD::SELECT, Node->getValueType(0), Tmp1, Tmp2,Tmp3);
583 switch (getTypeAction(Node->getOperand(0).getValueType())) {
585 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
586 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
587 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
588 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
592 assert(0 && "Can't promote setcc operands yet!");
595 SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
596 ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
597 ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
598 switch (cast<SetCCSDNode>(Node)->getCondition()) {
601 Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
602 Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
603 Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
604 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(), Tmp1,
605 DAG.getConstant(0, Tmp1.getValueType()));
608 // FIXME: This generated code sucks.
610 switch (cast<SetCCSDNode>(Node)->getCondition()) {
611 default: assert(0 && "Unknown integer setcc!");
613 case ISD::SETULT: LowCC = ISD::SETULT; break;
615 case ISD::SETUGT: LowCC = ISD::SETUGT; break;
617 case ISD::SETULE: LowCC = ISD::SETULE; break;
619 case ISD::SETUGE: LowCC = ISD::SETUGE; break;
622 // Tmp1 = lo(op1) < lo(op2) // Always unsigned comparison
623 // Tmp2 = hi(op1) < hi(op2) // Signedness depends on operands
624 // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
626 // NOTE: on targets without efficient SELECT of bools, we can always use
627 // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
628 Tmp1 = DAG.getSetCC(LowCC, LHSLo, RHSLo);
629 Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
631 Result = DAG.getSetCC(ISD::SETEQ, LHSHi, RHSHi);
632 Result = DAG.getNode(ISD::SELECT, MVT::i1, Result, Tmp1, Tmp2);
641 Tmp1 = LegalizeOp(Node->getOperand(0));
642 Tmp2 = LegalizeOp(Node->getOperand(1));
643 Tmp3 = LegalizeOp(Node->getOperand(2));
644 SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
645 SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
646 if (TLI.isOperationSupported(Node->getOpcode(), MVT::Other)) {
647 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
648 Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
649 Tmp5 != Node->getOperand(4)) {
650 std::vector<SDOperand> Ops;
651 Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
652 Ops.push_back(Tmp4); Ops.push_back(Tmp5);
653 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
656 // Otherwise, the target does not support this operation. Lower the
657 // operation to an explicit libcall as appropriate.
658 MVT::ValueType IntPtr = TLI.getPointerTy();
659 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
660 std::vector<std::pair<SDOperand, const Type*> > Args;
662 const char *FnName = 0;
663 if (Node->getOpcode() == ISD::MEMSET) {
664 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
665 // Extend the ubyte argument to be an int value for the call.
666 Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
667 Args.push_back(std::make_pair(Tmp3, Type::IntTy));
668 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
671 } else if (Node->getOpcode() == ISD::MEMCPY ||
672 Node->getOpcode() == ISD::MEMMOVE) {
673 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
674 Args.push_back(std::make_pair(Tmp3, IntPtrTy));
675 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
676 FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
678 assert(0 && "Unknown op!");
680 std::pair<SDOperand,SDOperand> CallResult =
681 TLI.LowerCallTo(Tmp1, Type::VoidTy,
682 DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
683 Result = LegalizeOp(CallResult.second);
700 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
701 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
702 if (Tmp1 != Node->getOperand(0) ||
703 Tmp2 != Node->getOperand(1))
704 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
706 case ISD::ZERO_EXTEND:
707 case ISD::SIGN_EXTEND:
711 case ISD::FP_TO_SINT:
712 case ISD::FP_TO_UINT:
713 case ISD::SINT_TO_FP:
714 case ISD::UINT_TO_FP:
716 switch (getTypeAction(Node->getOperand(0).getValueType())) {
718 Tmp1 = LegalizeOp(Node->getOperand(0));
719 if (Tmp1 != Node->getOperand(0))
720 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
723 assert(Node->getOpcode() != ISD::SINT_TO_FP &&
724 Node->getOpcode() != ISD::UINT_TO_FP &&
725 "Cannot lower Xint_to_fp to a call yet!");
727 // In the expand case, we must be dealing with a truncate, because
728 // otherwise the result would be larger than the source.
729 assert(Node->getOpcode() == ISD::TRUNCATE &&
730 "Shouldn't need to expand other operators here!");
731 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
733 // Since the result is legal, we should just be able to truncate the low
734 // part of the source.
735 Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
739 switch (Node->getOpcode()) {
740 case ISD::ZERO_EXTEND: {
741 // Mask out the high bits.
743 1ULL << (MVT::getSizeInBits(Node->getOperand(0).getValueType()))-1;
744 Tmp1 = PromoteOp(Node->getOperand(0));
745 Result = DAG.getNode(ISD::AND, Node->getValueType(0), Tmp1,
746 DAG.getConstant(MaskCst, Node->getValueType(0)));
749 case ISD::SIGN_EXTEND:
753 case ISD::FP_TO_SINT:
754 case ISD::FP_TO_UINT:
755 case ISD::SINT_TO_FP:
756 case ISD::UINT_TO_FP:
758 assert(0 && "Do not know how to promote this yet!");
762 case ISD::FP_ROUND_INREG:
763 case ISD::SIGN_EXTEND_INREG:
764 case ISD::ZERO_EXTEND_INREG: {
765 Tmp1 = LegalizeOp(Node->getOperand(0));
766 MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
768 // If this operation is not supported, convert it to a shl/shr or load/store
770 if (!TLI.isOperationSupported(Node->getOpcode(), ExtraVT)) {
771 // If this is an integer extend and shifts are supported, do that.
772 if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
773 // NOTE: we could fall back on load/store here too for targets without
774 // AND. However, it is doubtful that any exist.
775 // AND out the appropriate bits.
777 DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
778 Node->getValueType(0));
779 Result = DAG.getNode(ISD::AND, Node->getValueType(0),
780 Node->getOperand(0), Mask);
781 } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
782 // NOTE: we could fall back on load/store here too for targets without
783 // SAR. However, it is doubtful that any exist.
784 unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
785 MVT::getSizeInBits(ExtraVT);
786 SDOperand ShiftCst = DAG.getConstant(BitsDiff, MVT::i8);
787 Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
788 Node->getOperand(0), ShiftCst);
789 Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
791 } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
792 // The only way we can lower this is to turn it into a STORETRUNC,
793 // EXTLOAD pair, targetting a temporary location (a stack slot).
795 // NOTE: there is a choice here between constantly creating new stack
796 // slots and always reusing the same one. We currently always create
797 // new ones, as reuse may inhibit scheduling.
798 const Type *Ty = MVT::getTypeForValueType(ExtraVT);
799 unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
800 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
801 MachineFunction &MF = DAG.getMachineFunction();
803 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
804 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
805 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
806 Node->getOperand(0), StackSlot, ExtraVT);
807 Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
808 Result, StackSlot, ExtraVT);
810 assert(0 && "Unknown op");
812 Result = LegalizeOp(Result);
814 if (Tmp1 != Node->getOperand(0))
815 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
822 if (!Op.Val->hasOneUse())
823 AddLegalizedOperand(Op, Result);
828 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
829 MVT::ValueType VT = Op.getValueType();
830 MVT::ValueType NVT = TransformToType[VT];
831 assert(getTypeAction(VT) == Promote &&
832 "Caller should expand or legalize operands that are not promotable!");
833 assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
834 "Cannot promote to smaller type!");
836 std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
837 if (I != PromotedNodes.end()) return I->second;
839 SDOperand Tmp1, Tmp2, Tmp3;
842 SDNode *Node = Op.Val;
844 // Promotion needs an optimization step to clean up after it, and is not
845 // careful to avoid operations the target does not support. Make sure that
846 // all generated operations are legalized in the next iteration.
847 NeedsAnotherIteration = true;
849 switch (Node->getOpcode()) {
851 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
852 assert(0 && "Do not know how to promote this operator!");
855 Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
856 assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
858 case ISD::ConstantFP:
859 Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
860 assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
864 switch (getTypeAction(Node->getOperand(0).getValueType())) {
866 Result = LegalizeOp(Node->getOperand(0));
867 assert(Result.getValueType() >= NVT &&
868 "This truncation doesn't make sense!");
869 if (Result.getValueType() > NVT) // Truncate to NVT instead of VT
870 Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
873 assert(0 && "Cannot handle expand yet");
875 assert(0 && "Cannot handle promote-promote yet");
881 // The logical ops can just execute, they don't care what the top bits
883 Tmp1 = PromoteOp(Node->getOperand(0));
884 Tmp2 = PromoteOp(Node->getOperand(1));
885 assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
886 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
891 // The input may have strange things in the top bits of the registers, but
892 // these operations don't care. They may have wierd bits going out, but
893 // that too is okay if they are integer operations.
894 Tmp1 = PromoteOp(Node->getOperand(0));
895 Tmp2 = PromoteOp(Node->getOperand(1));
896 assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
897 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
899 // However, if this is a floating point operation, they will give excess
900 // precision that we may not be able to tolerate. If we DO allow excess
901 // precision, just leave it, otherwise excise it.
902 if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
903 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
907 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
908 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
909 Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
911 // Remember that we legalized the chain.
912 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
915 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition
916 Tmp2 = PromoteOp(Node->getOperand(1)); // Legalize the op0
917 Tmp3 = PromoteOp(Node->getOperand(2)); // Legalize the op1
918 Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
922 assert(Result.Val && "Didn't set a result!");
923 AddPromotedOperand(Op, Result);
927 /// ExpandOp - Expand the specified SDOperand into its two component pieces
928 /// Lo&Hi. Note that the Op MUST be an expanded type. As a result of this, the
929 /// LegalizeNodes map is filled in for any results that are not expanded, the
930 /// ExpandedNodes map is filled in for any results that are expanded, and the
931 /// Lo/Hi values are returned.
932 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
933 MVT::ValueType VT = Op.getValueType();
934 MVT::ValueType NVT = TransformToType[VT];
935 SDNode *Node = Op.Val;
936 assert(getTypeAction(VT) == Expand && "Not an expanded type!");
937 assert(MVT::isInteger(VT) && "Cannot expand FP values!");
938 assert(MVT::isInteger(NVT) && NVT < VT &&
939 "Cannot expand to FP value or to larger int value!");
941 // If there is more than one use of this, see if we already expanded it.
942 // There is no use remembering values that only have a single use, as the map
943 // entries will never be reused.
944 if (!Node->hasOneUse()) {
945 std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
946 = ExpandedNodes.find(Op);
947 if (I != ExpandedNodes.end()) {
948 Lo = I->second.first;
949 Hi = I->second.second;
954 // Expanding to multiple registers needs to perform an optimization step, and
955 // is not careful to avoid operations the target does not support. Make sure
956 // that all generated operations are legalized in the next iteration.
957 NeedsAnotherIteration = true;
958 const char *LibCallName = 0;
960 switch (Node->getOpcode()) {
962 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
963 assert(0 && "Do not know how to expand this operator!");
965 case ISD::Constant: {
966 uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
967 Lo = DAG.getConstant(Cst, NVT);
968 Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
972 case ISD::CopyFromReg: {
973 unsigned Reg = cast<RegSDNode>(Node)->getReg();
974 // Aggregate register values are always in consequtive pairs.
975 Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
976 Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
978 // Remember that we legalized the chain.
979 AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
981 assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
986 SDOperand Ch = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
987 SDOperand Ptr = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
988 Lo = DAG.getLoad(NVT, Ch, Ptr);
990 // Increment the pointer to the other half.
991 unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
992 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
993 getIntPtrConstant(IncrementSize));
994 // FIXME: This load is independent of the first one.
995 Hi = DAG.getLoad(NVT, Lo.getValue(1), Ptr);
997 // Remember that we legalized the chain.
998 AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
999 if (!TLI.isLittleEndian())
1004 SDOperand Chain = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1005 SDOperand Callee = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
1007 assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1008 "Can only expand a call once so far, not i64 -> i16!");
1010 std::vector<MVT::ValueType> RetTyVTs;
1011 RetTyVTs.reserve(3);
1012 RetTyVTs.push_back(NVT);
1013 RetTyVTs.push_back(NVT);
1014 RetTyVTs.push_back(MVT::Other);
1015 SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee);
1016 Lo = SDOperand(NC, 0);
1017 Hi = SDOperand(NC, 1);
1019 // Insert the new chain mapping.
1020 AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1025 case ISD::XOR: { // Simple logical operators -> two trivial pieces.
1026 SDOperand LL, LH, RL, RH;
1027 ExpandOp(Node->getOperand(0), LL, LH);
1028 ExpandOp(Node->getOperand(1), RL, RH);
1029 Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1030 Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1034 SDOperand C, LL, LH, RL, RH;
1035 // FIXME: BOOLS MAY REQUIRE PROMOTION!
1036 C = LegalizeOp(Node->getOperand(0));
1037 ExpandOp(Node->getOperand(1), LL, LH);
1038 ExpandOp(Node->getOperand(2), RL, RH);
1039 Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1040 Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1043 case ISD::SIGN_EXTEND: {
1044 // The low part is just a sign extension of the input (which degenerates to
1046 Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1048 // The high part is obtained by SRA'ing all but one of the bits of the lo
1050 unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1051 Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1, MVT::i8));
1054 case ISD::ZERO_EXTEND:
1055 // The low part is just a zero extension of the input (which degenerates to
1057 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1059 // The high part is just a zero.
1060 Hi = DAG.getConstant(0, NVT);
1063 // These operators cannot be expanded directly, emit them as calls to
1064 // library functions.
1065 case ISD::FP_TO_SINT:
1066 if (Node->getOperand(0).getValueType() == MVT::f32)
1067 LibCallName = "__fixsfdi";
1069 LibCallName = "__fixdfdi";
1071 case ISD::FP_TO_UINT:
1072 if (Node->getOperand(0).getValueType() == MVT::f32)
1073 LibCallName = "__fixunssfdi";
1075 LibCallName = "__fixunsdfdi";
1078 case ISD::ADD: LibCallName = "__adddi3"; break;
1079 case ISD::SUB: LibCallName = "__subdi3"; break;
1080 case ISD::MUL: LibCallName = "__muldi3"; break;
1081 case ISD::SDIV: LibCallName = "__divdi3"; break;
1082 case ISD::UDIV: LibCallName = "__udivdi3"; break;
1083 case ISD::SREM: LibCallName = "__moddi3"; break;
1084 case ISD::UREM: LibCallName = "__umoddi3"; break;
1085 case ISD::SHL: LibCallName = "__ashldi3"; break;
1086 case ISD::SRA: LibCallName = "__ashrdi3"; break;
1087 case ISD::SRL: LibCallName = "__lshrdi3"; break;
1090 // Int2FP -> __floatdisf/__floatdidf
1092 // If this is to be expanded into a libcall... do so now.
1094 TargetLowering::ArgListTy Args;
1095 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1096 Args.push_back(std::make_pair(Node->getOperand(i),
1097 MVT::getTypeForValueType(Node->getOperand(i).getValueType())));
1098 SDOperand Callee = DAG.getExternalSymbol(LibCallName, TLI.getPointerTy());
1100 // We don't care about token chains for libcalls. We just use the entry
1101 // node as our input and ignore the output chain. This allows us to place
1102 // calls wherever we need them to satisfy data dependences.
1103 SDOperand Result = TLI.LowerCallTo(DAG.getEntryNode(),
1104 MVT::getTypeForValueType(Op.getValueType()), Callee,
1106 ExpandOp(Result, Lo, Hi);
1109 // Remember in a map if the values will be reused later.
1110 if (!Node->hasOneUse()) {
1111 bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1112 std::make_pair(Lo, Hi))).second;
1113 assert(isNew && "Value already expanded?!?");
1118 // SelectionDAG::Legalize - This is the entry point for the file.
1120 void SelectionDAG::Legalize(TargetLowering &TLI) {
1121 /// run - This is the main entry point to this class.
1123 SelectionDAGLegalize(TLI, *this).Run();