blob: 72daa66bd575dc805a36110ee46a2304ed6f3b31 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeydcb2b832006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000073namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey03593f72006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner4333f8b2007-04-30 17:29:31 +000085namespace { struct AsmOperandInfo; }
86
Chris Lattner6f87d182006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000135 };
136}
Evan Chengc1e1d972006-01-23 07:01:07 +0000137
Chris Lattner7a60d912005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000175 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000185
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
190 }
Misha Brukman835702a2005-04-21 22:36:52 +0000191
Chris Lattner49409cb2006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner7a60d912005-01-07 07:47:53 +0000194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
198 }
199 };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattner6871b232005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000217/// entry block, return true. This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000219static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner7a60d912005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattner6871b232005-10-30 19:42:35 +0000231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 AI != E; ++AI)
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
237
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
240 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000247 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000248 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000250
Reid Spencere0fc4df2006-10-20 07:07:24 +0000251 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000252 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 StaticAllocaMap[AI] =
Chris Lattnercb0ed0c2007-04-25 04:08:28 +0000254 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000255 }
256
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000257 for (; BB != EB; ++BB)
258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000259 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
260 if (!isa<AllocaInst>(I) ||
261 !StaticAllocaMap.count(cast<AllocaInst>(I)))
262 InitializeRegForValue(I);
263
264 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
265 // also creates the initial PHI MachineInstrs, though none of the input
266 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000267 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000268 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
269 MBBMap[BB] = MBB;
270 MF.getBasicBlockList().push_back(MBB);
271
272 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
273 // appropriate.
274 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000275 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
276 if (PN->use_empty()) continue;
277
278 MVT::ValueType VT = TLI.getValueType(PN->getType());
279 unsigned NumElements;
280 if (VT != MVT::Vector)
281 NumElements = TLI.getNumElements(VT);
282 else {
283 MVT::ValueType VT1,VT2;
284 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000285 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000286 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000287 }
Chris Lattner84a03502006-10-27 23:50:33 +0000288 unsigned PHIReg = ValueMap[PN];
289 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000290 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000291 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000292 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000293 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000294 }
295}
296
Chris Lattner49409cb2006-03-16 19:51:18 +0000297/// CreateRegForValue - Allocate the appropriate number of virtual registers of
298/// the correctly promoted or expanded types. Assign these registers
299/// consecutive vreg numbers and return the first assigned number.
300unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
301 MVT::ValueType VT = TLI.getValueType(V->getType());
302
303 // The number of multiples of registers that we need, to, e.g., split up
304 // a <2 x int64> -> 4 x i32 registers.
305 unsigned NumVectorRegs = 1;
306
Reid Spencer09575ba2007-02-15 03:39:18 +0000307 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000308 // and how many of the elements it will use.
309 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000310 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000311 unsigned NumElts = PTy->getNumElements();
312 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Dan Gohman1796f1f2007-05-18 17:52:13 +0000313 MVT::ValueType VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000314
315 // Divide the input until we get to a supported size. This will always
316 // end with a scalar if the target doesn't support vectors.
Bill Wendling47917b62007-04-24 21:13:23 +0000317 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner49409cb2006-03-16 19:51:18 +0000318 NumElts >>= 1;
319 NumVectorRegs <<= 1;
Dan Gohman1796f1f2007-05-18 17:52:13 +0000320 VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000321 }
Bill Wendling47917b62007-04-24 21:13:23 +0000322
323 // Check that VecTy isn't a 1-element vector.
324 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner7ececaa2006-03-16 23:05:19 +0000325 VT = EltTy;
326 else
Bill Wendling47917b62007-04-24 21:13:23 +0000327 VT = VecTy;
Chris Lattner49409cb2006-03-16 19:51:18 +0000328 }
Bill Wendling47917b62007-04-24 21:13:23 +0000329
Chris Lattner49409cb2006-03-16 19:51:18 +0000330 // The common case is that we will only create one register for this
331 // value. If we have that case, create and return the virtual register.
332 unsigned NV = TLI.getNumElements(VT);
333 if (NV == 1) {
334 // If we are promoting this value, pick the next largest supported type.
335 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
336 unsigned Reg = MakeReg(PromotedType);
337 // If this is a vector of supported or promoted types (e.g. 4 x i16),
338 // create all of the registers.
339 for (unsigned i = 1; i != NumVectorRegs; ++i)
340 MakeReg(PromotedType);
341 return Reg;
342 }
343
344 // If this value is represented with multiple target registers, make sure
345 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000346 VT = TLI.getTypeToExpandTo(VT);
347 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000349 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000350 return R;
351}
Chris Lattner7a60d912005-01-07 07:47:53 +0000352
353//===----------------------------------------------------------------------===//
354/// SelectionDAGLowering - This is the common target-independent lowering
355/// implementation that is parameterized by a TargetLowering object.
356/// Also, targets can overload any lowering method.
357///
358namespace llvm {
359class SelectionDAGLowering {
360 MachineBasicBlock *CurMBB;
361
Chris Lattner79084302007-02-04 01:31:47 +0000362 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000363
Chris Lattner4d9651c2005-01-17 22:19:26 +0000364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
365 /// them up and then emit token factor nodes when possible. This allows us to
366 /// get simple disambiguation between loads without worrying about alias
367 /// analysis.
368 std::vector<SDOperand> PendingLoads;
369
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000370 /// Case - A struct to record the Value for a switch case, and the
371 /// case's target basic block.
372 struct Case {
373 Constant* Low;
374 Constant* High;
375 MachineBasicBlock* BB;
376
377 Case() : Low(0), High(0), BB(0) { }
378 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
379 Low(low), High(high), BB(bb) { }
380 uint64_t size() const {
381 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
382 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
383 return (rHigh - rLow + 1ULL);
384 }
385 };
386
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000387 struct CaseBits {
388 uint64_t Mask;
389 MachineBasicBlock* BB;
390 unsigned Bits;
391
392 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
393 Mask(mask), BB(bb), Bits(bits) { }
394 };
395
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000396 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000397 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000398 typedef CaseVector::iterator CaseItr;
399 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000400
401 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
402 /// of conditional branches.
403 struct CaseRec {
404 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
405 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
406
407 /// CaseBB - The MBB in which to emit the compare and branch
408 MachineBasicBlock *CaseBB;
409 /// LT, GE - If nonzero, we know the current case value must be less-than or
410 /// greater-than-or-equal-to these Constants.
411 Constant *LT;
412 Constant *GE;
413 /// Range - A pair of iterators representing the range of case values to be
414 /// processed at this point in the binary search tree.
415 CaseRange Range;
416 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000417
418 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000419
420 /// The comparison function for sorting the switch case values in the vector.
421 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000422 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000423 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000424 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
425 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
426 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
427 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000428 }
429 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000430
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000431 struct CaseBitsCmp {
432 bool operator () (const CaseBits& C1, const CaseBits& C2) {
433 return C1.Bits > C2.Bits;
434 }
435 };
436
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000437 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000438
Chris Lattner7a60d912005-01-07 07:47:53 +0000439public:
440 // TLI - This is information that describes the available target features we
441 // need for lowering. This indicates when operations are unavailable,
442 // implemented with a libcall, etc.
443 TargetLowering &TLI;
444 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000445 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000446
Nate Begemaned728c12006-03-27 01:32:24 +0000447 /// SwitchCases - Vector of CaseBlock structures used to communicate
448 /// SwitchInst code generation information.
449 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000450 /// JTCases - Vector of JumpTable structures used to communicate
451 /// SwitchInst code generation information.
452 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000453 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000454
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 /// FuncInfo - Information about the function as a whole.
456 ///
457 FunctionLoweringInfo &FuncInfo;
458
459 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000460 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000462 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000463 }
464
Chris Lattner4108bb02005-01-17 19:43:36 +0000465 /// getRoot - Return the current virtual root of the Selection DAG.
466 ///
467 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000468 if (PendingLoads.empty())
469 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000470
Chris Lattner4d9651c2005-01-17 22:19:26 +0000471 if (PendingLoads.size() == 1) {
472 SDOperand Root = PendingLoads[0];
473 DAG.setRoot(Root);
474 PendingLoads.clear();
475 return Root;
476 }
477
478 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000479 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
480 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000481 PendingLoads.clear();
482 DAG.setRoot(Root);
483 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000484 }
485
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 void visit(Instruction &I) { visit(I.getOpcode(), I); }
489
490 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000491 // Note: this doesn't use InstVisitor, because it has to work with
492 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 switch (Opcode) {
494 default: assert(0 && "Unknown instruction type encountered!");
495 abort();
496 // Build the switch statement using the Instruction.def file.
497#define HANDLE_INST(NUM, OPCODE, CLASS) \
498 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
499#include "llvm/Instruction.def"
500 }
501 }
502
503 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
504
Chris Lattner4024c002006-03-15 22:19:46 +0000505 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000506 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000507 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000508
509 SDOperand getIntPtrConstant(uint64_t Val) {
510 return DAG.getConstant(Val, TLI.getPointerTy());
511 }
512
Chris Lattner8471b152006-03-16 19:57:50 +0000513 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000514
Chris Lattner79084302007-02-04 01:31:47 +0000515 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 SDOperand &N = NodeMap[V];
517 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000518 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000519 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000520
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000521 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
522 std::set<unsigned> &OutputRegs,
523 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000524
Chris Lattnered0110b2006-10-27 21:36:01 +0000525 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
526 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
527 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000528 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000529 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000530 void LowerCallTo(Instruction &I,
531 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000532 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
533 MachineBasicBlock *LandingPad = NULL);
534
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 // Terminator instructions.
536 void visitRet(ReturnInst &I);
537 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000538 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000539 void visitUnreachable(UnreachableInst &I) { /* noop */ }
540
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000541 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000542 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000543 CaseRecVector& WorkList,
544 Value* SV,
545 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000546 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000547 CaseRecVector& WorkList,
548 Value* SV,
549 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000550 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000551 CaseRecVector& WorkList,
552 Value* SV,
553 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000554 bool handleBitTestsSwitchCase(CaseRec& CR,
555 CaseRecVector& WorkList,
556 Value* SV,
557 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000558 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000559 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
560 void visitBitTestCase(MachineBasicBlock* NextMBB,
561 unsigned Reg,
562 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000563 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000564 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
565 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000566
Chris Lattner7a60d912005-01-07 07:47:53 +0000567 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000568 void visitInvoke(InvokeInst &I);
569 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000570
Reid Spencer2eadb532007-01-21 00:29:26 +0000571 void visitScalarBinary(User &I, unsigned OpCode);
572 void visitVectorBinary(User &I, unsigned OpCode);
573 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000574 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000575 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000576 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000577 visitVectorBinary(I, ISD::VADD);
578 else if (I.getType()->isFloatingPoint())
579 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000580 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000581 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000582 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000583 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000584 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000585 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000586 visitVectorBinary(I, ISD::VMUL);
587 else if (I.getType()->isFloatingPoint())
588 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000589 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000590 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000591 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000592 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
593 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
594 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
595 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
596 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
597 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
598 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
599 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
600 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
601 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000602 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
603 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000604 void visitICmp(User &I);
605 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000606 // Visit the conversion instructions
607 void visitTrunc(User &I);
608 void visitZExt(User &I);
609 void visitSExt(User &I);
610 void visitFPTrunc(User &I);
611 void visitFPExt(User &I);
612 void visitFPToUI(User &I);
613 void visitFPToSI(User &I);
614 void visitUIToFP(User &I);
615 void visitSIToFP(User &I);
616 void visitPtrToInt(User &I);
617 void visitIntToPtr(User &I);
618 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000619
Chris Lattner67271862006-03-29 00:11:43 +0000620 void visitExtractElement(User &I);
621 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000622 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000623
Chris Lattner7a60d912005-01-07 07:47:53 +0000624 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000625 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000626
627 void visitMalloc(MallocInst &I);
628 void visitFree(FreeInst &I);
629 void visitAlloca(AllocaInst &I);
630 void visitLoad(LoadInst &I);
631 void visitStore(StoreInst &I);
632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
633 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000634 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000637
Chris Lattner7a60d912005-01-07 07:47:53 +0000638 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000639 void visitVAArg(VAArgInst &I);
640 void visitVAEnd(CallInst &I);
641 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000642
Chris Lattner875def92005-01-11 05:56:49 +0000643 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000644
645 void visitUserOp1(Instruction &I) {
646 assert(0 && "UserOp1 should not exist at instruction selection time!");
647 abort();
648 }
649 void visitUserOp2(Instruction &I) {
650 assert(0 && "UserOp2 should not exist at instruction selection time!");
651 abort();
652 }
653};
654} // end namespace llvm
655
Chris Lattner8471b152006-03-16 19:57:50 +0000656SDOperand SelectionDAGLowering::getValue(const Value *V) {
657 SDOperand &N = NodeMap[V];
658 if (N.Val) return N;
659
660 const Type *VTy = V->getType();
661 MVT::ValueType VT = TLI.getValueType(VTy);
662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
664 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000665 SDOperand N1 = NodeMap[V];
666 assert(N1.Val && "visit didn't populate the ValueMap!");
667 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
669 return N = DAG.getGlobalAddress(GV, VT);
670 } else if (isa<ConstantPointerNull>(C)) {
671 return N = DAG.getConstant(0, TLI.getPointerTy());
672 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000673 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000674 return N = DAG.getNode(ISD::UNDEF, VT);
675
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000676 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000677 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000678 unsigned NumElements = PTy->getNumElements();
679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
680
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000681 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
683
684 // Create a VConstant node with generic Vector type.
685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
686 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000687 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
688 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000689 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
690 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000691 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000692 unsigned NumElements = PTy->getNumElements();
693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000694
695 // Now that we know the number and type of the elements, push a
696 // Constant or ConstantFP node onto the ops list for each element of
697 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000698 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000699 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000700 for (unsigned i = 0; i != NumElements; ++i)
701 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000702 } else {
703 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
704 SDOperand Op;
705 if (MVT::isFloatingPoint(PVT))
706 Op = DAG.getConstantFP(0, PVT);
707 else
708 Op = DAG.getConstant(0, PVT);
709 Ops.assign(NumElements, Op);
710 }
711
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000712 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000713 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
714 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000715 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
716 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000717 } else {
718 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000719 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000720 }
721 }
722
723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
724 std::map<const AllocaInst*, int>::iterator SI =
725 FuncInfo.StaticAllocaMap.find(AI);
726 if (SI != FuncInfo.StaticAllocaMap.end())
727 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
728 }
729
Chris Lattner8c504cf2007-02-25 18:40:32 +0000730 unsigned InReg = FuncInfo.ValueMap[V];
731 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000732
733 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000734 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000735 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000736 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000737 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000738 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
739 unsigned NumVals = TLI.getNumElements(VT);
740 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
741 if (NumVals == 1)
742 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
743 else {
744 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
745 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
746 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
747 }
748 } else {
749 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
750 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
751 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
752 N = MVT::isFloatingPoint(VT)
753 ? DAG.getNode(ISD::FP_ROUND, VT, N)
754 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000755 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000756 } else {
757 // Otherwise, if this is a vector, make it available as a generic vector
758 // here.
759 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000760 const VectorType *PTy = cast<VectorType>(VTy);
761 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000762 PTyLegalElementVT);
763
764 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000765 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000766 if (PTyElementVT == PTyLegalElementVT) {
767 // If the value types are legal, just VBUILD the CopyFromReg nodes.
768 for (unsigned i = 0; i != NE; ++i)
769 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
770 PTyElementVT));
771 } else if (PTyElementVT < PTyLegalElementVT) {
Dan Gohman30978072007-05-24 14:36:04 +0000772 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000773 for (unsigned i = 0; i != NE; ++i) {
774 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
775 PTyElementVT);
776 if (MVT::isFloatingPoint(PTyElementVT))
777 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
778 else
779 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
780 Ops.push_back(Op);
781 }
782 } else {
783 // If the register was expanded, use BUILD_PAIR.
784 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
785 for (unsigned i = 0; i != NE/2; ++i) {
786 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
787 PTyElementVT);
788 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
789 PTyElementVT);
790 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
791 }
792 }
793
794 Ops.push_back(DAG.getConstant(NE, MVT::i32));
795 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000796 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000797
798 // Finally, use a VBIT_CONVERT to make this available as the appropriate
799 // vector type.
800 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
801 DAG.getConstant(PTy->getNumElements(),
802 MVT::i32),
803 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000804 }
805
806 return N;
807}
808
809
Chris Lattner7a60d912005-01-07 07:47:53 +0000810void SelectionDAGLowering::visitRet(ReturnInst &I) {
811 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000812 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000813 return;
814 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000815 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000816 NewValues.push_back(getRoot());
817 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
818 SDOperand RetOp = getValue(I.getOperand(i));
819
820 // If this is an integer return value, we need to promote it ourselves to
821 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
822 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000823 // FIXME: C calling convention requires the return type to be promoted to
824 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000825 if (MVT::isInteger(RetOp.getValueType()) &&
826 RetOp.getValueType() < MVT::i64) {
827 MVT::ValueType TmpVT;
828 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
829 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
830 else
831 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000832 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000833 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000834 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000835 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000836 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000837 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000838 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000839 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000840 }
841 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000842 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000843 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000844 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
845 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000846}
847
Chris Lattnered0110b2006-10-27 21:36:01 +0000848/// ExportFromCurrentBlock - If this condition isn't known to be exported from
849/// the current basic block, add it to ValueMap now so that we'll get a
850/// CopyTo/FromReg.
851void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
852 // No need to export constants.
853 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
854
855 // Already exported?
856 if (FuncInfo.isExportedInst(V)) return;
857
858 unsigned Reg = FuncInfo.InitializeRegForValue(V);
859 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
860}
861
Chris Lattner84a03502006-10-27 23:50:33 +0000862bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
863 const BasicBlock *FromBB) {
864 // The operands of the setcc have to be in this block. We don't know
865 // how to export them from some other block.
866 if (Instruction *VI = dyn_cast<Instruction>(V)) {
867 // Can export from current BB.
868 if (VI->getParent() == FromBB)
869 return true;
870
871 // Is already exported, noop.
872 return FuncInfo.isExportedInst(V);
873 }
874
875 // If this is an argument, we can export it if the BB is the entry block or
876 // if it is already exported.
877 if (isa<Argument>(V)) {
878 if (FromBB == &FromBB->getParent()->getEntryBlock())
879 return true;
880
881 // Otherwise, can only export this if it is already exported.
882 return FuncInfo.isExportedInst(V);
883 }
884
885 // Otherwise, constants can always be exported.
886 return true;
887}
888
Chris Lattnere60ae822006-10-29 21:01:20 +0000889static bool InBlock(const Value *V, const BasicBlock *BB) {
890 if (const Instruction *I = dyn_cast<Instruction>(V))
891 return I->getParent() == BB;
892 return true;
893}
894
Chris Lattnered0110b2006-10-27 21:36:01 +0000895/// FindMergedConditions - If Cond is an expression like
896void SelectionDAGLowering::FindMergedConditions(Value *Cond,
897 MachineBasicBlock *TBB,
898 MachineBasicBlock *FBB,
899 MachineBasicBlock *CurBB,
900 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000901 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000902 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000903
Reid Spencer266e42b2006-12-23 06:05:41 +0000904 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
905 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000906 BOp->getParent() != CurBB->getBasicBlock() ||
907 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
908 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000909 const BasicBlock *BB = CurBB->getBasicBlock();
910
Reid Spencer266e42b2006-12-23 06:05:41 +0000911 // If the leaf of the tree is a comparison, merge the condition into
912 // the caseblock.
913 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
914 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000915 // how to export them from some other block. If this is the first block
916 // of the sequence, no exporting is needed.
917 (CurBB == CurMBB ||
918 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
919 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000920 BOp = cast<Instruction>(Cond);
921 ISD::CondCode Condition;
922 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
923 switch (IC->getPredicate()) {
924 default: assert(0 && "Unknown icmp predicate opcode!");
925 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
926 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
927 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
928 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
929 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
930 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
931 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
932 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
933 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
934 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
935 }
936 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
937 ISD::CondCode FPC, FOC;
938 switch (FC->getPredicate()) {
939 default: assert(0 && "Unknown fcmp predicate opcode!");
940 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
941 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
942 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
943 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
944 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
945 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
946 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
947 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
948 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
949 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
950 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
951 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
952 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
953 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
954 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
955 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
956 }
957 if (FiniteOnlyFPMath())
958 Condition = FOC;
959 else
960 Condition = FPC;
961 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000962 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000963 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000964 }
965
Chris Lattnered0110b2006-10-27 21:36:01 +0000966 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000967 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000968 SwitchCases.push_back(CB);
969 return;
970 }
971
972 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000973 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000974 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000975 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000976 return;
977 }
978
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000979
980 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000981 MachineFunction::iterator BBI = CurBB;
982 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
983 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
984
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000985 if (Opc == Instruction::Or) {
986 // Codegen X | Y as:
987 // jmp_if_X TBB
988 // jmp TmpBB
989 // TmpBB:
990 // jmp_if_Y TBB
991 // jmp FBB
992 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000993
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000994 // Emit the LHS condition.
995 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
996
997 // Emit the RHS condition into TmpBB.
998 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
999 } else {
1000 assert(Opc == Instruction::And && "Unknown merge op!");
1001 // Codegen X & Y as:
1002 // jmp_if_X TmpBB
1003 // jmp FBB
1004 // TmpBB:
1005 // jmp_if_Y TBB
1006 // jmp FBB
1007 //
1008 // This requires creation of TmpBB after CurBB.
1009
1010 // Emit the LHS condition.
1011 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1012
1013 // Emit the RHS condition into TmpBB.
1014 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1015 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001016}
1017
Chris Lattner427301f2006-10-31 22:37:42 +00001018/// If the set of cases should be emitted as a series of branches, return true.
1019/// If we should emit this as a bunch of and/or'd together conditions, return
1020/// false.
1021static bool
1022ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1023 if (Cases.size() != 2) return true;
1024
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001025 // If this is two comparisons of the same values or'd or and'd together, they
1026 // will get folded into a single comparison, so don't emit two blocks.
1027 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1028 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1029 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1030 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1031 return false;
1032 }
1033
Chris Lattner427301f2006-10-31 22:37:42 +00001034 return true;
1035}
1036
Chris Lattner7a60d912005-01-07 07:47:53 +00001037void SelectionDAGLowering::visitBr(BranchInst &I) {
1038 // Update machine-CFG edges.
1039 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001040
1041 // Figure out which block is immediately after the current one.
1042 MachineBasicBlock *NextBlock = 0;
1043 MachineFunction::iterator BBI = CurMBB;
1044 if (++BBI != CurMBB->getParent()->end())
1045 NextBlock = BBI;
1046
1047 if (I.isUnconditional()) {
1048 // If this is not a fall-through branch, emit the branch.
1049 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001050 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001051 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001052
Chris Lattner963ddad2006-10-24 17:57:59 +00001053 // Update machine-CFG edges.
1054 CurMBB->addSuccessor(Succ0MBB);
1055
1056 return;
1057 }
1058
1059 // If this condition is one of the special cases we handle, do special stuff
1060 // now.
1061 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001062 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001063
1064 // If this is a series of conditions that are or'd or and'd together, emit
1065 // this as a sequence of branches instead of setcc's with and/or operations.
1066 // For example, instead of something like:
1067 // cmp A, B
1068 // C = seteq
1069 // cmp D, E
1070 // F = setle
1071 // or C, F
1072 // jnz foo
1073 // Emit:
1074 // cmp A, B
1075 // je foo
1076 // cmp D, E
1077 // jle foo
1078 //
1079 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1080 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001081 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001082 BOp->getOpcode() == Instruction::Or)) {
1083 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001084 // If the compares in later blocks need to use values not currently
1085 // exported from this block, export them now. This block should always
1086 // be the first entry.
1087 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1088
Chris Lattner427301f2006-10-31 22:37:42 +00001089 // Allow some cases to be rejected.
1090 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001091 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1092 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1093 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1094 }
1095
1096 // Emit the branch for this block.
1097 visitSwitchCase(SwitchCases[0]);
1098 SwitchCases.erase(SwitchCases.begin());
1099 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001100 }
1101
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001102 // Okay, we decided not to do this, remove any inserted MBB's and clear
1103 // SwitchCases.
1104 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1105 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1106
Chris Lattner427301f2006-10-31 22:37:42 +00001107 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001108 }
1109 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001110
1111 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001112 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001113 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001114 // Use visitSwitchCase to actually insert the fast branch sequence for this
1115 // cond branch.
1116 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001117}
1118
Nate Begemaned728c12006-03-27 01:32:24 +00001119/// visitSwitchCase - Emits the necessary code to represent a single node in
1120/// the binary search tree resulting from lowering a switch instruction.
1121void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001122 SDOperand Cond;
1123 SDOperand CondLHS = getValue(CB.CmpLHS);
1124
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001125 // Build the setcc now.
1126 if (CB.CmpMHS == NULL) {
1127 // Fold "(X == true)" to X and "(X == false)" to !X to
1128 // handle common cases produced by branch lowering.
1129 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1130 Cond = CondLHS;
1131 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1132 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1133 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1134 } else
1135 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1136 } else {
1137 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001138
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001139 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1140 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1141
1142 SDOperand CmpOp = getValue(CB.CmpMHS);
1143 MVT::ValueType VT = CmpOp.getValueType();
1144
1145 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1146 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1147 } else {
1148 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1149 Cond = DAG.getSetCC(MVT::i1, SUB,
1150 DAG.getConstant(High-Low, VT), ISD::SETULE);
1151 }
1152
1153 }
1154
Nate Begemaned728c12006-03-27 01:32:24 +00001155 // Set NextBlock to be the MBB immediately after the current one, if any.
1156 // This is used to avoid emitting unnecessary branches to the next block.
1157 MachineBasicBlock *NextBlock = 0;
1158 MachineFunction::iterator BBI = CurMBB;
1159 if (++BBI != CurMBB->getParent()->end())
1160 NextBlock = BBI;
1161
1162 // If the lhs block is the next block, invert the condition so that we can
1163 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001164 if (CB.TrueBB == NextBlock) {
1165 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001166 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1167 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1168 }
1169 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001170 DAG.getBasicBlock(CB.TrueBB));
1171 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001172 DAG.setRoot(BrCond);
1173 else
1174 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001175 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001176 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001177 CurMBB->addSuccessor(CB.TrueBB);
1178 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001179}
1180
Anton Korobeynikov70378262007-03-25 15:07:15 +00001181/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001182void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001183 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001184 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001185 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001186 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1187 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1188 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1189 Table, Index));
1190 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001191}
1192
Anton Korobeynikov70378262007-03-25 15:07:15 +00001193/// visitJumpTableHeader - This function emits necessary code to produce index
1194/// in the JumpTable from switch case.
1195void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1196 SelectionDAGISel::JumpTableHeader &JTH) {
1197 // Subtract the lowest switch case value from the value being switched on
1198 // and conditional branch to default mbb if the result is greater than the
1199 // difference between smallest and largest cases.
1200 SDOperand SwitchOp = getValue(JTH.SValue);
1201 MVT::ValueType VT = SwitchOp.getValueType();
1202 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1203 DAG.getConstant(JTH.First, VT));
1204
1205 // The SDNode we just created, which holds the value being switched on
1206 // minus the the smallest case value, needs to be copied to a virtual
1207 // register so it can be used as an index into the jump table in a
1208 // subsequent basic block. This value may be smaller or larger than the
1209 // target's pointer type, and therefore require extension or truncating.
1210 if (VT > TLI.getPointerTy())
1211 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1212 else
1213 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1214
1215 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1216 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1217 JT.Reg = JumpTableReg;
1218
1219 // Emit the range check for the jump table, and branch to the default
1220 // block for the switch statement if the value being switched on exceeds
1221 // the largest case in the switch.
1222 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1223 DAG.getConstant(JTH.Last-JTH.First,VT),
1224 ISD::SETUGT);
1225
1226 // Set NextBlock to be the MBB immediately after the current one, if any.
1227 // This is used to avoid emitting unnecessary branches to the next block.
1228 MachineBasicBlock *NextBlock = 0;
1229 MachineFunction::iterator BBI = CurMBB;
1230 if (++BBI != CurMBB->getParent()->end())
1231 NextBlock = BBI;
1232
1233 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1234 DAG.getBasicBlock(JT.Default));
1235
1236 if (JT.MBB == NextBlock)
1237 DAG.setRoot(BrCond);
1238 else
1239 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001240 DAG.getBasicBlock(JT.MBB)));
1241
1242 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001243}
1244
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001245/// visitBitTestHeader - This function emits necessary code to produce value
1246/// suitable for "bit tests"
1247void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1248 // Subtract the minimum value
1249 SDOperand SwitchOp = getValue(B.SValue);
1250 MVT::ValueType VT = SwitchOp.getValueType();
1251 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1252 DAG.getConstant(B.First, VT));
1253
1254 // Check range
1255 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1256 DAG.getConstant(B.Range, VT),
1257 ISD::SETUGT);
1258
1259 SDOperand ShiftOp;
1260 if (VT > TLI.getShiftAmountTy())
1261 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1262 else
1263 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1264
1265 // Make desired shift
1266 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1267 DAG.getConstant(1, TLI.getPointerTy()),
1268 ShiftOp);
1269
1270 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1271 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1272 B.Reg = SwitchReg;
1273
1274 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1275 DAG.getBasicBlock(B.Default));
1276
1277 // Set NextBlock to be the MBB immediately after the current one, if any.
1278 // This is used to avoid emitting unnecessary branches to the next block.
1279 MachineBasicBlock *NextBlock = 0;
1280 MachineFunction::iterator BBI = CurMBB;
1281 if (++BBI != CurMBB->getParent()->end())
1282 NextBlock = BBI;
1283
1284 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1285 if (MBB == NextBlock)
1286 DAG.setRoot(BrRange);
1287 else
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1289 DAG.getBasicBlock(MBB)));
1290
1291 CurMBB->addSuccessor(B.Default);
1292 CurMBB->addSuccessor(MBB);
1293
1294 return;
1295}
1296
1297/// visitBitTestCase - this function produces one "bit test"
1298void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1299 unsigned Reg,
1300 SelectionDAGISel::BitTestCase &B) {
1301 // Emit bit tests and jumps
1302 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1303
1304 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1305 SwitchVal,
1306 DAG.getConstant(B.Mask,
1307 TLI.getPointerTy()));
1308 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1309 DAG.getConstant(0, TLI.getPointerTy()),
1310 ISD::SETNE);
1311 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1312 AndCmp, DAG.getBasicBlock(B.TargetBB));
1313
1314 // Set NextBlock to be the MBB immediately after the current one, if any.
1315 // This is used to avoid emitting unnecessary branches to the next block.
1316 MachineBasicBlock *NextBlock = 0;
1317 MachineFunction::iterator BBI = CurMBB;
1318 if (++BBI != CurMBB->getParent()->end())
1319 NextBlock = BBI;
1320
1321 if (NextMBB == NextBlock)
1322 DAG.setRoot(BrAnd);
1323 else
1324 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1325 DAG.getBasicBlock(NextMBB)));
1326
1327 CurMBB->addSuccessor(B.TargetBB);
1328 CurMBB->addSuccessor(NextMBB);
1329
1330 return;
1331}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001332
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001333void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1334 // Retrieve successors.
1335 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001336 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001337
Duncan Sands97f72362007-06-13 05:51:31 +00001338 LowerCallTo(I, I.getCalledValue()->getType(),
1339 I.getCallingConv(),
1340 false,
1341 getValue(I.getOperand(0)),
1342 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001343
Duncan Sands97f72362007-06-13 05:51:31 +00001344 // If the value of the invoke is used outside of its defining block, make it
1345 // available as a virtual register.
1346 if (!I.use_empty()) {
1347 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1348 if (VMI != FuncInfo.ValueMap.end())
1349 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey14059d92007-02-25 21:43:59 +00001350 }
Duncan Sands97f72362007-06-13 05:51:31 +00001351
1352 // Drop into normal successor.
1353 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1354 DAG.getBasicBlock(Return)));
1355
1356 // Update successor info
1357 CurMBB->addSuccessor(Return);
1358 CurMBB->addSuccessor(LandingPad);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001359}
1360
1361void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1362}
1363
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001364/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001365/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001366bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001367 CaseRecVector& WorkList,
1368 Value* SV,
1369 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001370 Case& BackCase = *(CR.Range.second-1);
1371
1372 // Size is the number of Cases represented by this range.
1373 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001374 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001375 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001376
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001377 // Get the MachineFunction which holds the current MBB. This is used when
1378 // inserting any additional MBBs necessary to represent the switch.
1379 MachineFunction *CurMF = CurMBB->getParent();
1380
1381 // Figure out which block is immediately after the current one.
1382 MachineBasicBlock *NextBlock = 0;
1383 MachineFunction::iterator BBI = CR.CaseBB;
1384
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001385 if (++BBI != CurMBB->getParent()->end())
1386 NextBlock = BBI;
1387
1388 // TODO: If any two of the cases has the same destination, and if one value
1389 // is the same as the other, but has one bit unset that the other has set,
1390 // use bit manipulation to do two compares at once. For example:
1391 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1392
1393 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001394 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001395 // The last case block won't fall through into 'NextBlock' if we emit the
1396 // branches in this order. See if rearranging a case value would help.
1397 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001398 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001399 std::swap(*I, BackCase);
1400 break;
1401 }
1402 }
1403 }
1404
1405 // Create a CaseBlock record representing a conditional branch to
1406 // the Case's target mbb if the value being switched on SV is equal
1407 // to C.
1408 MachineBasicBlock *CurBlock = CR.CaseBB;
1409 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1410 MachineBasicBlock *FallThrough;
1411 if (I != E-1) {
1412 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1413 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1414 } else {
1415 // If the last case doesn't match, go to the default block.
1416 FallThrough = Default;
1417 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001418
1419 Value *RHS, *LHS, *MHS;
1420 ISD::CondCode CC;
1421 if (I->High == I->Low) {
1422 // This is just small small case range :) containing exactly 1 case
1423 CC = ISD::SETEQ;
1424 LHS = SV; RHS = I->High; MHS = NULL;
1425 } else {
1426 CC = ISD::SETLE;
1427 LHS = I->Low; MHS = SV; RHS = I->High;
1428 }
1429 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1430 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001431
1432 // If emitting the first comparison, just call visitSwitchCase to emit the
1433 // code into the current block. Otherwise, push the CaseBlock onto the
1434 // vector to be later processed by SDISel, and insert the node's MBB
1435 // before the next MBB.
1436 if (CurBlock == CurMBB)
1437 visitSwitchCase(CB);
1438 else
1439 SwitchCases.push_back(CB);
1440
1441 CurBlock = FallThrough;
1442 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001443
1444 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001445}
1446
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001447static inline bool areJTsAllowed(const TargetLowering &TLI) {
1448 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1449 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1450}
1451
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001452/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001453bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001454 CaseRecVector& WorkList,
1455 Value* SV,
1456 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001457 Case& FrontCase = *CR.Range.first;
1458 Case& BackCase = *(CR.Range.second-1);
1459
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001460 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1461 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1462
1463 uint64_t TSize = 0;
1464 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1465 I!=E; ++I)
1466 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001467
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001468 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001469 return false;
1470
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001471 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1472 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001473 return false;
1474
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001475 DOUT << "Lowering jump table\n"
1476 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001477 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001478
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001479 // Get the MachineFunction which holds the current MBB. This is used when
1480 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001481 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001482
1483 // Figure out which block is immediately after the current one.
1484 MachineBasicBlock *NextBlock = 0;
1485 MachineFunction::iterator BBI = CR.CaseBB;
1486
1487 if (++BBI != CurMBB->getParent()->end())
1488 NextBlock = BBI;
1489
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001490 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1491
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001492 // Create a new basic block to hold the code for loading the address
1493 // of the jump table, and jumping to it. Update successor information;
1494 // we will either branch to the default case for the switch, or the jump
1495 // table.
1496 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1497 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1498 CR.CaseBB->addSuccessor(Default);
1499 CR.CaseBB->addSuccessor(JumpTableBB);
1500
1501 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001502 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001503 // a case statement, push the case's BB onto the vector, otherwise, push
1504 // the default BB.
1505 std::vector<MachineBasicBlock*> DestBBs;
1506 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001507 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1508 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1509 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1510
1511 if ((Low <= TEI) && (TEI <= High)) {
1512 DestBBs.push_back(I->BB);
1513 if (TEI==High)
1514 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001515 } else {
1516 DestBBs.push_back(Default);
1517 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001518 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001519
1520 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001521 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001522 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1523 E = DestBBs.end(); I != E; ++I) {
1524 if (!SuccsHandled[(*I)->getNumber()]) {
1525 SuccsHandled[(*I)->getNumber()] = true;
1526 JumpTableBB->addSuccessor(*I);
1527 }
1528 }
1529
1530 // Create a jump table index for this jump table, or return an existing
1531 // one.
1532 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1533
1534 // Set the jump table information so that we can codegen it as a second
1535 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001536 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001537 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1538 (CR.CaseBB == CurMBB));
1539 if (CR.CaseBB == CurMBB)
1540 visitJumpTableHeader(JT, JTH);
1541
1542 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001543
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001544 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001545}
1546
1547/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1548/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001549bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001550 CaseRecVector& WorkList,
1551 Value* SV,
1552 MachineBasicBlock* Default) {
1553 // Get the MachineFunction which holds the current MBB. This is used when
1554 // inserting any additional MBBs necessary to represent the switch.
1555 MachineFunction *CurMF = CurMBB->getParent();
1556
1557 // Figure out which block is immediately after the current one.
1558 MachineBasicBlock *NextBlock = 0;
1559 MachineFunction::iterator BBI = CR.CaseBB;
1560
1561 if (++BBI != CurMBB->getParent()->end())
1562 NextBlock = BBI;
1563
1564 Case& FrontCase = *CR.Range.first;
1565 Case& BackCase = *(CR.Range.second-1);
1566 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1567
1568 // Size is the number of Cases represented by this range.
1569 unsigned Size = CR.Range.second - CR.Range.first;
1570
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001571 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1572 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001573 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001574 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001575
1576 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1577 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001578 uint64_t TSize = 0;
1579 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1580 I!=E; ++I)
1581 TSize += I->size();
1582
1583 uint64_t LSize = FrontCase.size();
1584 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001585 DOUT << "Selecting best pivot: \n"
1586 << "First: " << First << ", Last: " << Last <<"\n"
1587 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001588 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001589 J!=E; ++I, ++J) {
1590 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1591 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001592 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001593 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1594 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001595 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001596 // Should always split in some non-trivial place
1597 DOUT <<"=>Step\n"
1598 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1599 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1600 << "Metric: " << Metric << "\n";
1601 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001602 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001603 FMetric = Metric;
1604 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001605 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001606
1607 LSize += J->size();
1608 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001609 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001610 if (areJTsAllowed(TLI)) {
1611 // If our case is dense we *really* should handle it earlier!
1612 assert((FMetric > 0) && "Should handle dense range earlier!");
1613 } else {
1614 Pivot = CR.Range.first + Size/2;
1615 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001616
1617 CaseRange LHSR(CR.Range.first, Pivot);
1618 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001619 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001620 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1621
1622 // We know that we branch to the LHS if the Value being switched on is
1623 // less than the Pivot value, C. We use this to optimize our binary
1624 // tree a bit, by recognizing that if SV is greater than or equal to the
1625 // LHS's Case Value, and that Case Value is exactly one less than the
1626 // Pivot's Value, then we can branch directly to the LHS's Target,
1627 // rather than creating a leaf node for it.
1628 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001629 LHSR.first->High == CR.GE &&
1630 cast<ConstantInt>(C)->getSExtValue() ==
1631 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1632 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001633 } else {
1634 TrueBB = new MachineBasicBlock(LLVMBB);
1635 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1636 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1637 }
1638
1639 // Similar to the optimization above, if the Value being switched on is
1640 // known to be less than the Constant CR.LT, and the current Case Value
1641 // is CR.LT - 1, then we can branch directly to the target block for
1642 // the current Case Value, rather than emitting a RHS leaf node for it.
1643 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001644 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1645 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1646 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001647 } else {
1648 FalseBB = new MachineBasicBlock(LLVMBB);
1649 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1650 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1651 }
1652
1653 // Create a CaseBlock record representing a conditional branch to
1654 // the LHS node if the value being switched on SV is less than C.
1655 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001656 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1657 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001658
1659 if (CR.CaseBB == CurMBB)
1660 visitSwitchCase(CB);
1661 else
1662 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001663
1664 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001665}
1666
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001667/// handleBitTestsSwitchCase - if current case range has few destination and
1668/// range span less, than machine word bitwidth, encode case range into series
1669/// of masks and emit bit tests with these masks.
1670bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1671 CaseRecVector& WorkList,
1672 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001673 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001674 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001675
1676 Case& FrontCase = *CR.Range.first;
1677 Case& BackCase = *(CR.Range.second-1);
1678
1679 // Get the MachineFunction which holds the current MBB. This is used when
1680 // inserting any additional MBBs necessary to represent the switch.
1681 MachineFunction *CurMF = CurMBB->getParent();
1682
1683 unsigned numCmps = 0;
1684 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1685 I!=E; ++I) {
1686 // Single case counts one, case range - two.
1687 if (I->Low == I->High)
1688 numCmps +=1;
1689 else
1690 numCmps +=2;
1691 }
1692
1693 // Count unique destinations
1694 SmallSet<MachineBasicBlock*, 4> Dests;
1695 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1696 Dests.insert(I->BB);
1697 if (Dests.size() > 3)
1698 // Don't bother the code below, if there are too much unique destinations
1699 return false;
1700 }
1701 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1702 << "Total number of comparisons: " << numCmps << "\n";
1703
1704 // Compute span of values.
1705 Constant* minValue = FrontCase.Low;
1706 Constant* maxValue = BackCase.High;
1707 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1708 cast<ConstantInt>(minValue)->getSExtValue();
1709 DOUT << "Compare range: " << range << "\n"
1710 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1711 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1712
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001713 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001714 (!(Dests.size() == 1 && numCmps >= 3) &&
1715 !(Dests.size() == 2 && numCmps >= 5) &&
1716 !(Dests.size() >= 3 && numCmps >= 6)))
1717 return false;
1718
1719 DOUT << "Emitting bit tests\n";
1720 int64_t lowBound = 0;
1721
1722 // Optimize the case where all the case values fit in a
1723 // word without having to subtract minValue. In this case,
1724 // we can optimize away the subtraction.
1725 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001726 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001727 range = cast<ConstantInt>(maxValue)->getSExtValue();
1728 } else {
1729 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1730 }
1731
1732 CaseBitsVector CasesBits;
1733 unsigned i, count = 0;
1734
1735 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1736 MachineBasicBlock* Dest = I->BB;
1737 for (i = 0; i < count; ++i)
1738 if (Dest == CasesBits[i].BB)
1739 break;
1740
1741 if (i == count) {
1742 assert((count < 3) && "Too much destinations to test!");
1743 CasesBits.push_back(CaseBits(0, Dest, 0));
1744 count++;
1745 }
1746
1747 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1748 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1749
1750 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001751 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001752 CasesBits[i].Bits++;
1753 }
1754
1755 }
1756 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1757
1758 SelectionDAGISel::BitTestInfo BTC;
1759
1760 // Figure out which block is immediately after the current one.
1761 MachineFunction::iterator BBI = CR.CaseBB;
1762 ++BBI;
1763
1764 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1765
1766 DOUT << "Cases:\n";
1767 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1768 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1769 << ", BB: " << CasesBits[i].BB << "\n";
1770
1771 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1772 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1773 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1774 CaseBB,
1775 CasesBits[i].BB));
1776 }
1777
1778 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001779 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001780 CR.CaseBB, Default, BTC);
1781
1782 if (CR.CaseBB == CurMBB)
1783 visitBitTestHeader(BTB);
1784
1785 BitTestCases.push_back(BTB);
1786
1787 return true;
1788}
1789
1790
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001791// Clusterify - Transform simple list of Cases into list of CaseRange's
1792unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1793 const SwitchInst& SI) {
1794 unsigned numCmps = 0;
1795
1796 // Start with "simple" cases
1797 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1798 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1799 Cases.push_back(Case(SI.getSuccessorValue(i),
1800 SI.getSuccessorValue(i),
1801 SMBB));
1802 }
1803 sort(Cases.begin(), Cases.end(), CaseCmp());
1804
1805 // Merge case into clusters
1806 if (Cases.size()>=2)
1807 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1808 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1809 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1810 MachineBasicBlock* nextBB = J->BB;
1811 MachineBasicBlock* currentBB = I->BB;
1812
1813 // If the two neighboring cases go to the same destination, merge them
1814 // into a single case.
1815 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1816 I->High = J->High;
1817 J = Cases.erase(J);
1818 } else {
1819 I = J++;
1820 }
1821 }
1822
1823 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1824 if (I->Low != I->High)
1825 // A range counts double, since it requires two compares.
1826 ++numCmps;
1827 }
1828
1829 return numCmps;
1830}
1831
1832void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001833 // Figure out which block is immediately after the current one.
1834 MachineBasicBlock *NextBlock = 0;
1835 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001836
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001837 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001838
Nate Begemaned728c12006-03-27 01:32:24 +00001839 // If there is only the default destination, branch to it if it is not the
1840 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001841 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001842 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001843
Nate Begemaned728c12006-03-27 01:32:24 +00001844 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001845 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001846 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001847 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001848
Chris Lattner6d6fc262006-10-22 21:36:53 +00001849 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001850 return;
1851 }
1852
1853 // If there are any non-default case statements, create a vector of Cases
1854 // representing each one, and sort the vector so that we can efficiently
1855 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001856 CaseVector Cases;
1857 unsigned numCmps = Clusterify(Cases, SI);
1858 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1859 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001860
Nate Begemaned728c12006-03-27 01:32:24 +00001861 // Get the Value to be switched on and default basic blocks, which will be
1862 // inserted into CaseBlock records, representing basic blocks in the binary
1863 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001864 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001865
Nate Begemaned728c12006-03-27 01:32:24 +00001866 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001867 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001868 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1869
1870 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001871 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001872 CaseRec CR = WorkList.back();
1873 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001874
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001875 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1876 continue;
1877
Anton Korobeynikov70378262007-03-25 15:07:15 +00001878 // If the range has few cases (two or less) emit a series of specific
1879 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001880 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1881 continue;
1882
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001883 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001884 // target supports indirect branches, then emit a jump table rather than
1885 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001886 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1887 continue;
1888
1889 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1890 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1891 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001892 }
1893}
1894
Anton Korobeynikov70378262007-03-25 15:07:15 +00001895
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001896void SelectionDAGLowering::visitSub(User &I) {
1897 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001898 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001899 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001900 visitVectorBinary(I, ISD::VSUB);
1901 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001902 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1903 if (CFP->isExactlyValue(-0.0)) {
1904 SDOperand Op2 = getValue(I.getOperand(1));
1905 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1906 return;
1907 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001908 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001909 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001910 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001911}
1912
Reid Spencer2eadb532007-01-21 00:29:26 +00001913void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001914 SDOperand Op1 = getValue(I.getOperand(0));
1915 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001916
1917 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001918}
1919
Reid Spencer2eadb532007-01-21 00:29:26 +00001920void
1921SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001922 assert(isa<VectorType>(I.getType()));
1923 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001924 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001925
Reid Spencer2eadb532007-01-21 00:29:26 +00001926 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1927 getValue(I.getOperand(0)),
1928 getValue(I.getOperand(1)),
1929 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1930 Typ));
1931}
1932
1933void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1934 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001935 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001936 visitVectorBinary(I, VectorOp);
1937 else
1938 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001939}
Chris Lattner96c26752005-01-19 22:31:21 +00001940
Nate Begeman127321b2005-11-18 07:42:56 +00001941void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1942 SDOperand Op1 = getValue(I.getOperand(0));
1943 SDOperand Op2 = getValue(I.getOperand(1));
1944
Reid Spencer2341c222007-02-02 02:16:23 +00001945 if (TLI.getShiftAmountTy() < Op2.getValueType())
1946 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1947 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1948 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001949
Chris Lattner7a60d912005-01-07 07:47:53 +00001950 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1951}
1952
Reid Spencerd9436b62006-11-20 01:22:35 +00001953void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001954 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1955 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1956 predicate = IC->getPredicate();
1957 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1958 predicate = ICmpInst::Predicate(IC->getPredicate());
1959 SDOperand Op1 = getValue(I.getOperand(0));
1960 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001961 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001962 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001963 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1964 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1965 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1966 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1967 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1968 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1969 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1970 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1971 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1972 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1973 default:
1974 assert(!"Invalid ICmp predicate value");
1975 Opcode = ISD::SETEQ;
1976 break;
1977 }
1978 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1979}
1980
1981void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001982 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1983 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1984 predicate = FC->getPredicate();
1985 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1986 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001987 SDOperand Op1 = getValue(I.getOperand(0));
1988 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001989 ISD::CondCode Condition, FOC, FPC;
1990 switch (predicate) {
1991 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1992 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1993 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1994 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1995 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1996 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1997 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1998 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1999 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2000 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2001 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2002 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2003 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2004 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2005 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2006 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2007 default:
2008 assert(!"Invalid FCmp predicate value");
2009 FOC = FPC = ISD::SETFALSE;
2010 break;
2011 }
2012 if (FiniteOnlyFPMath())
2013 Condition = FOC;
2014 else
2015 Condition = FPC;
2016 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00002017}
2018
2019void SelectionDAGLowering::visitSelect(User &I) {
2020 SDOperand Cond = getValue(I.getOperand(0));
2021 SDOperand TrueVal = getValue(I.getOperand(1));
2022 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002023 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00002024 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2025 TrueVal, FalseVal));
2026 } else {
2027 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2028 *(TrueVal.Val->op_end()-2),
2029 *(TrueVal.Val->op_end()-1)));
2030 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002031}
2032
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002033
2034void SelectionDAGLowering::visitTrunc(User &I) {
2035 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2036 SDOperand N = getValue(I.getOperand(0));
2037 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2038 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2039}
2040
2041void SelectionDAGLowering::visitZExt(User &I) {
2042 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2043 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2044 SDOperand N = getValue(I.getOperand(0));
2045 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2046 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2047}
2048
2049void SelectionDAGLowering::visitSExt(User &I) {
2050 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2051 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2052 SDOperand N = getValue(I.getOperand(0));
2053 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2054 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2055}
2056
2057void SelectionDAGLowering::visitFPTrunc(User &I) {
2058 // FPTrunc is never a no-op cast, no need to check
2059 SDOperand N = getValue(I.getOperand(0));
2060 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2061 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2062}
2063
2064void SelectionDAGLowering::visitFPExt(User &I){
2065 // FPTrunc is never a no-op cast, no need to check
2066 SDOperand N = getValue(I.getOperand(0));
2067 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2068 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2069}
2070
2071void SelectionDAGLowering::visitFPToUI(User &I) {
2072 // FPToUI is never a no-op cast, no need to check
2073 SDOperand N = getValue(I.getOperand(0));
2074 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2075 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2076}
2077
2078void SelectionDAGLowering::visitFPToSI(User &I) {
2079 // FPToSI is never a no-op cast, no need to check
2080 SDOperand N = getValue(I.getOperand(0));
2081 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2082 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2083}
2084
2085void SelectionDAGLowering::visitUIToFP(User &I) {
2086 // UIToFP is never a no-op cast, no need to check
2087 SDOperand N = getValue(I.getOperand(0));
2088 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2089 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2090}
2091
2092void SelectionDAGLowering::visitSIToFP(User &I){
2093 // UIToFP is never a no-op cast, no need to check
2094 SDOperand N = getValue(I.getOperand(0));
2095 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2096 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2097}
2098
2099void SelectionDAGLowering::visitPtrToInt(User &I) {
2100 // What to do depends on the size of the integer and the size of the pointer.
2101 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002102 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002103 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002104 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002105 SDOperand Result;
2106 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2107 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2108 else
2109 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2110 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2111 setValue(&I, Result);
2112}
Chris Lattner7a60d912005-01-07 07:47:53 +00002113
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002114void SelectionDAGLowering::visitIntToPtr(User &I) {
2115 // What to do depends on the size of the integer and the size of the pointer.
2116 // We can either truncate, zero extend, or no-op, accordingly.
2117 SDOperand N = getValue(I.getOperand(0));
2118 MVT::ValueType SrcVT = N.getValueType();
2119 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2120 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2121 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2122 else
2123 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2124 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2125}
2126
2127void SelectionDAGLowering::visitBitCast(User &I) {
2128 SDOperand N = getValue(I.getOperand(0));
2129 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002130 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002131 // This is a cast to a vector from something else.
2132 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002133 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002134 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2135 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2136 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2137 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002138 return;
2139 }
2140 MVT::ValueType SrcVT = N.getValueType();
2141 if (SrcVT == MVT::Vector) {
2142 // This is a cast from a vctor to something else.
2143 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00002144 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002145 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002146 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002147
2148 // BitCast assures us that source and destination are the same size so this
2149 // is either a BIT_CONVERT or a no-op.
2150 if (DestVT != N.getValueType())
2151 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2152 else
2153 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002154}
2155
Chris Lattner67271862006-03-29 00:11:43 +00002156void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002157 SDOperand InVec = getValue(I.getOperand(0));
2158 SDOperand InVal = getValue(I.getOperand(1));
2159 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2160 getValue(I.getOperand(2)));
2161
Chris Lattner29b23012006-03-19 01:17:20 +00002162 SDOperand Num = *(InVec.Val->op_end()-2);
2163 SDOperand Typ = *(InVec.Val->op_end()-1);
2164 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2165 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00002166}
2167
Chris Lattner67271862006-03-29 00:11:43 +00002168void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002169 SDOperand InVec = getValue(I.getOperand(0));
2170 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2171 getValue(I.getOperand(1)));
2172 SDOperand Typ = *(InVec.Val->op_end()-1);
2173 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2174 TLI.getValueType(I.getType()), InVec, InIdx));
2175}
Chris Lattner32206f52006-03-18 01:44:44 +00002176
Chris Lattner098c01e2006-04-08 04:15:24 +00002177void SelectionDAGLowering::visitShuffleVector(User &I) {
2178 SDOperand V1 = getValue(I.getOperand(0));
2179 SDOperand V2 = getValue(I.getOperand(1));
2180 SDOperand Mask = getValue(I.getOperand(2));
2181
2182 SDOperand Num = *(V1.Val->op_end()-2);
2183 SDOperand Typ = *(V2.Val->op_end()-1);
2184 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2185 V1, V2, Mask, Num, Typ));
2186}
2187
2188
Chris Lattner7a60d912005-01-07 07:47:53 +00002189void SelectionDAGLowering::visitGetElementPtr(User &I) {
2190 SDOperand N = getValue(I.getOperand(0));
2191 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002192
2193 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2194 OI != E; ++OI) {
2195 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002196 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002197 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002198 if (Field) {
2199 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002200 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002201 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002202 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002203 }
2204 Ty = StTy->getElementType(Field);
2205 } else {
2206 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002207
Chris Lattner43535a12005-11-09 04:45:33 +00002208 // If this is a constant subscript, handle it quickly.
2209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002210 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002211 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002212 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002213 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2214 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002215 }
Chris Lattner43535a12005-11-09 04:45:33 +00002216
2217 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002218 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002219 SDOperand IdxN = getValue(Idx);
2220
2221 // If the index is smaller or larger than intptr_t, truncate or extend
2222 // it.
2223 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002224 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002225 } else if (IdxN.getValueType() > N.getValueType())
2226 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2227
2228 // If this is a multiply by a power of two, turn it into a shl
2229 // immediately. This is a very common case.
2230 if (isPowerOf2_64(ElementSize)) {
2231 unsigned Amt = Log2_64(ElementSize);
2232 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002233 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002234 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2235 continue;
2236 }
2237
2238 SDOperand Scale = getIntPtrConstant(ElementSize);
2239 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2240 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002241 }
2242 }
2243 setValue(&I, N);
2244}
2245
2246void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2247 // If this is a fixed sized alloca in the entry block of the function,
2248 // allocate it statically on the stack.
2249 if (FuncInfo.StaticAllocaMap.count(&I))
2250 return; // getValue will auto-populate this.
2251
2252 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002253 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002254 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002255 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002256 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002257
2258 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002259 MVT::ValueType IntPtr = TLI.getPointerTy();
2260 if (IntPtr < AllocSize.getValueType())
2261 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2262 else if (IntPtr > AllocSize.getValueType())
2263 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002264
Chris Lattnereccb73d2005-01-22 23:04:37 +00002265 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002266 getIntPtrConstant(TySize));
2267
2268 // Handle alignment. If the requested alignment is less than or equal to the
2269 // stack alignment, ignore it and round the size of the allocation up to the
2270 // stack alignment size. If the size is greater than the stack alignment, we
2271 // note this in the DYNAMIC_STACKALLOC node.
2272 unsigned StackAlign =
2273 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2274 if (Align <= StackAlign) {
2275 Align = 0;
2276 // Add SA-1 to the size.
2277 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2278 getIntPtrConstant(StackAlign-1));
2279 // Mask out the low bits for alignment purposes.
2280 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2281 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2282 }
2283
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002284 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002285 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2286 MVT::Other);
2287 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002288 setValue(&I, DSA);
2289 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002290
2291 // Inform the Frame Information that we have just allocated a variable-sized
2292 // object.
2293 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2294}
2295
Chris Lattner7a60d912005-01-07 07:47:53 +00002296void SelectionDAGLowering::visitLoad(LoadInst &I) {
2297 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002298
Chris Lattner4d9651c2005-01-17 22:19:26 +00002299 SDOperand Root;
2300 if (I.isVolatile())
2301 Root = getRoot();
2302 else {
2303 // Do not serialize non-volatile loads against each other.
2304 Root = DAG.getRoot();
2305 }
Chris Lattner4024c002006-03-15 22:19:46 +00002306
Evan Chenge71fe34d2006-10-09 20:57:25 +00002307 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002308 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002309}
2310
2311SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002312 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002313 bool isVolatile,
2314 unsigned Alignment) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002315 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002316 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002317 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002318 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2319 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002320 } else {
Christopher Lamb8af6d582007-04-22 23:15:30 +00002321 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2322 isVolatile, Alignment);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002323 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002324
Chris Lattner4024c002006-03-15 22:19:46 +00002325 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002326 DAG.setRoot(L.getValue(1));
2327 else
2328 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002329
2330 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002331}
2332
2333
2334void SelectionDAGLowering::visitStore(StoreInst &I) {
2335 Value *SrcV = I.getOperand(0);
2336 SDOperand Src = getValue(SrcV);
2337 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002338 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002339 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002340}
2341
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002342/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2343/// access memory and has no other side effects at all.
2344static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2345#define GET_NO_MEMORY_INTRINSICS
2346#include "llvm/Intrinsics.gen"
2347#undef GET_NO_MEMORY_INTRINSICS
2348 return false;
2349}
2350
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002351// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2352// have any side-effects or if it only reads memory.
2353static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2354#define GET_SIDE_EFFECT_INFO
2355#include "llvm/Intrinsics.gen"
2356#undef GET_SIDE_EFFECT_INFO
2357 return false;
2358}
2359
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002360/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2361/// node.
2362void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2363 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002364 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002365 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002366
2367 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002368 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002369 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2370 if (OnlyLoad) {
2371 // We don't need to serialize loads against other loads.
2372 Ops.push_back(DAG.getRoot());
2373 } else {
2374 Ops.push_back(getRoot());
2375 }
2376 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002377
2378 // Add the intrinsic ID as an integer operand.
2379 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2380
2381 // Add all operands of the call to the operand list.
2382 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2383 SDOperand Op = getValue(I.getOperand(i));
2384
Reid Spencer09575ba2007-02-15 03:39:18 +00002385 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002386 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002387 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002388 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2389
2390 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2391 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2392 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2393 }
2394
2395 assert(TLI.isTypeLegal(Op.getValueType()) &&
2396 "Intrinsic uses a non-legal type?");
2397 Ops.push_back(Op);
2398 }
2399
2400 std::vector<MVT::ValueType> VTs;
2401 if (I.getType() != Type::VoidTy) {
2402 MVT::ValueType VT = TLI.getValueType(I.getType());
2403 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002404 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002405 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2406
2407 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2408 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2409 }
2410
2411 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2412 VTs.push_back(VT);
2413 }
2414 if (HasChain)
2415 VTs.push_back(MVT::Other);
2416
Chris Lattnerbd887772006-08-14 23:53:35 +00002417 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2418
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002419 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002420 SDOperand Result;
2421 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002422 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2423 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002424 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002425 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2426 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002427 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002428 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2429 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002430
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002431 if (HasChain) {
2432 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2433 if (OnlyLoad)
2434 PendingLoads.push_back(Chain);
2435 else
2436 DAG.setRoot(Chain);
2437 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002438 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002439 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002440 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2441 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2442 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2443 DAG.getValueType(EVT));
2444 }
2445 setValue(&I, Result);
2446 }
2447}
2448
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002449/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2450/// (possibly constant folded), return it. Otherwise return NULL.
2451static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2452 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2453 return GV;
2454 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2455 if (CE->getOpcode() == Instruction::BitCast)
2456 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2457 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2458 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2459 if (!CE->getOperand(i)->isNullValue())
2460 return NULL;
2461 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2462 }
2463 }
2464 return NULL;
2465}
2466
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002467/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2468/// we want to emit this as a call to a named external function, return the name
2469/// otherwise lower it and return null.
2470const char *
2471SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2472 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002473 default:
2474 // By default, turn this into a target intrinsic node.
2475 visitTargetIntrinsic(I, Intrinsic);
2476 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002477 case Intrinsic::vastart: visitVAStart(I); return 0;
2478 case Intrinsic::vaend: visitVAEnd(I); return 0;
2479 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002480 case Intrinsic::returnaddress:
2481 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2482 getValue(I.getOperand(1))));
2483 return 0;
2484 case Intrinsic::frameaddress:
2485 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2486 getValue(I.getOperand(1))));
2487 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002488 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002489 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002490 break;
2491 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002492 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002493 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002494 case Intrinsic::memcpy_i32:
2495 case Intrinsic::memcpy_i64:
2496 visitMemIntrinsic(I, ISD::MEMCPY);
2497 return 0;
2498 case Intrinsic::memset_i32:
2499 case Intrinsic::memset_i64:
2500 visitMemIntrinsic(I, ISD::MEMSET);
2501 return 0;
2502 case Intrinsic::memmove_i32:
2503 case Intrinsic::memmove_i64:
2504 visitMemIntrinsic(I, ISD::MEMMOVE);
2505 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002506
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002507 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002508 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002509 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002510 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002511 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002512
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002513 Ops[0] = getRoot();
2514 Ops[1] = getValue(SPI.getLineValue());
2515 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002516
Jim Laskeyc56315c2007-01-26 21:22:28 +00002517 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002518 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002519 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2520
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002521 Ops[3] = DAG.getString(CompileUnit->getFileName());
2522 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002523
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002524 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002525 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002526
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002527 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002528 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002529 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002530 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002531 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002532 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2533 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002534 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002535 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002536 }
2537
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002538 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002539 }
2540 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002541 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002542 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002543 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2544 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002545 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002546 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002547 }
2548
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002549 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002550 }
2551 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002552 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002553 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002554 if (MMI && FSI.getSubprogram() &&
2555 MMI->Verify(FSI.getSubprogram())) {
2556 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002557 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002558 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002559 }
2560
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002561 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002562 }
2563 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002565 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002566 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002567 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002568 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002569 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002570 }
2571
2572 return 0;
2573 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002574
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002575 case Intrinsic::eh_exception: {
2576 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2577
Jim Laskey504e9942007-02-22 15:38:06 +00002578 if (MMI) {
Jim Laskey504e9942007-02-22 15:38:06 +00002579 // Mark exception register as live in.
2580 unsigned Reg = TLI.getExceptionAddressRegister();
2581 if (Reg) CurMBB->addLiveIn(Reg);
Duncan Sands61166502007-06-06 10:05:18 +00002582
Jim Laskey504e9942007-02-22 15:38:06 +00002583 // Insert the EXCEPTIONADDR instruction.
2584 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2585 SDOperand Ops[1];
2586 Ops[0] = DAG.getRoot();
2587 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2588 setValue(&I, Op);
2589 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002590 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002591 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002592 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002593 return 0;
2594 }
2595
Jim Laskeyd5453d72007-03-01 20:24:30 +00002596 case Intrinsic::eh_selector:
2597 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002598 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2599
Jim Laskey504e9942007-02-22 15:38:06 +00002600 if (MMI) {
2601 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002602 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2603 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2604 isa<Function>(CE->getOperand(0)) &&
2605 "Personality should be a function");
2606 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002607
Jim Laskey504e9942007-02-22 15:38:06 +00002608 // Gather all the type infos for this landing pad and pass them along to
2609 // MachineModuleInfo.
2610 std::vector<GlobalVariable *> TyInfo;
2611 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Anton Korobeynikova8fd7fd2007-05-06 20:14:21 +00002612 Constant *C = cast<Constant>(I.getOperand(i));
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002613 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002614 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002615 "TypeInfo must be a global variable or NULL");
2616 TyInfo.push_back(GV);
Jim Laskey504e9942007-02-22 15:38:06 +00002617 }
Duncan Sandsc063f5f2007-06-02 16:53:42 +00002618 if (Intrinsic == Intrinsic::eh_filter)
2619 MMI->addFilterTypeInfo(CurMBB, TyInfo);
2620 else
2621 MMI->addCatchTypeInfo(CurMBB, TyInfo);
Duncan Sands61166502007-06-06 10:05:18 +00002622
Jim Laskey504e9942007-02-22 15:38:06 +00002623 // Mark exception selector register as live in.
2624 unsigned Reg = TLI.getExceptionSelectorRegister();
2625 if (Reg) CurMBB->addLiveIn(Reg);
2626
2627 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002628 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002629 SDOperand Ops[2];
2630 Ops[0] = getValue(I.getOperand(1));
2631 Ops[1] = getRoot();
2632 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2633 setValue(&I, Op);
2634 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002635 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002636 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002637 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002638
2639 return 0;
2640 }
2641
2642 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002643 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002644
Jim Laskey504e9942007-02-22 15:38:06 +00002645 if (MMI) {
2646 // Find the type id for the given typeinfo.
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002647 Constant *C = cast<Constant>(I.getOperand(1));
2648 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002649 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002650 "TypeInfo must be a global variable or NULL");
2651
Jim Laskey504e9942007-02-22 15:38:06 +00002652 unsigned TypeID = MMI->getTypeIDFor(GV);
2653 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002654 } else {
2655 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002656 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002657
2658 return 0;
2659 }
2660
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002661 case Intrinsic::sqrt_f32:
2662 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002663 setValue(&I, DAG.getNode(ISD::FSQRT,
2664 getValue(I.getOperand(1)).getValueType(),
2665 getValue(I.getOperand(1))));
2666 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002667 case Intrinsic::powi_f32:
2668 case Intrinsic::powi_f64:
2669 setValue(&I, DAG.getNode(ISD::FPOWI,
2670 getValue(I.getOperand(1)).getValueType(),
2671 getValue(I.getOperand(1)),
2672 getValue(I.getOperand(2))));
2673 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002674 case Intrinsic::pcmarker: {
2675 SDOperand Tmp = getValue(I.getOperand(1));
2676 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2677 return 0;
2678 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002679 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002680 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002681 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2682 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2683 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002684 setValue(&I, Tmp);
2685 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002686 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002687 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002688 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002689 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002690 assert(0 && "part_select intrinsic not implemented");
2691 abort();
2692 }
2693 case Intrinsic::part_set: {
2694 // Currently not implemented: just abort
2695 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002696 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002697 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002698 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002699 setValue(&I, DAG.getNode(ISD::BSWAP,
2700 getValue(I.getOperand(1)).getValueType(),
2701 getValue(I.getOperand(1))));
2702 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002703 case Intrinsic::cttz: {
2704 SDOperand Arg = getValue(I.getOperand(1));
2705 MVT::ValueType Ty = Arg.getValueType();
2706 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2707 if (Ty < MVT::i32)
2708 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2709 else if (Ty > MVT::i32)
2710 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2711 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002712 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002713 }
2714 case Intrinsic::ctlz: {
2715 SDOperand Arg = getValue(I.getOperand(1));
2716 MVT::ValueType Ty = Arg.getValueType();
2717 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2718 if (Ty < MVT::i32)
2719 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2720 else if (Ty > MVT::i32)
2721 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2722 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002723 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002724 }
2725 case Intrinsic::ctpop: {
2726 SDOperand Arg = getValue(I.getOperand(1));
2727 MVT::ValueType Ty = Arg.getValueType();
2728 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2729 if (Ty < MVT::i32)
2730 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2731 else if (Ty > MVT::i32)
2732 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2733 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002734 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002735 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002736 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002737 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002738 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2739 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002740 setValue(&I, Tmp);
2741 DAG.setRoot(Tmp.getValue(1));
2742 return 0;
2743 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002744 case Intrinsic::stackrestore: {
2745 SDOperand Tmp = getValue(I.getOperand(1));
2746 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002747 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002748 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002749 case Intrinsic::prefetch:
2750 // FIXME: Currently discarding prefetches.
2751 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002752 }
2753}
2754
2755
Jim Laskey31fef782007-02-23 21:45:01 +00002756void SelectionDAGLowering::LowerCallTo(Instruction &I,
2757 const Type *CalledValueTy,
2758 unsigned CallingConv,
2759 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002760 SDOperand Callee, unsigned OpIdx,
2761 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002762 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002763 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002764 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002765 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2766 unsigned BeginLabel = 0, EndLabel = 0;
2767
Jim Laskey504e9942007-02-22 15:38:06 +00002768 TargetLowering::ArgListTy Args;
2769 TargetLowering::ArgListEntry Entry;
2770 Args.reserve(I.getNumOperands());
2771 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2772 Value *Arg = I.getOperand(i);
2773 SDOperand ArgNode = getValue(Arg);
2774 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands671e8c42007-05-07 20:49:28 +00002775
2776 unsigned attrInd = i - OpIdx + 1;
2777 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2778 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2779 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2780 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002781 Args.push_back(Entry);
2782 }
2783
Duncan Sands61166502007-06-06 10:05:18 +00002784 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002785 // Insert a label before the invoke call to mark the try range. This can be
2786 // used to detect deletion of the invoke via the MachineModuleInfo.
2787 BeginLabel = MMI->NextLabelID();
2788 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2789 DAG.getConstant(BeginLabel, MVT::i32)));
2790 }
2791
Jim Laskey504e9942007-02-22 15:38:06 +00002792 std::pair<SDOperand,SDOperand> Result =
2793 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002794 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002795 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002796 Callee, Args, DAG);
2797 if (I.getType() != Type::VoidTy)
2798 setValue(&I, Result.first);
2799 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002800
Duncan Sands61166502007-06-06 10:05:18 +00002801 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002802 // Insert a label at the end of the invoke call to mark the try range. This
2803 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2804 EndLabel = MMI->NextLabelID();
2805 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2806 DAG.getConstant(EndLabel, MVT::i32)));
2807
2808 // Inform MachineModuleInfo of range.
2809 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2810 }
Jim Laskey504e9942007-02-22 15:38:06 +00002811}
2812
2813
Chris Lattner7a60d912005-01-07 07:47:53 +00002814void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002815 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002816 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002817 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002818 if (unsigned IID = F->getIntrinsicID()) {
2819 RenameFn = visitIntrinsicCall(I, IID);
2820 if (!RenameFn)
2821 return;
2822 } else { // Not an LLVM intrinsic.
2823 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002824 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2825 if (I.getNumOperands() == 3 && // Basic sanity checks.
2826 I.getOperand(1)->getType()->isFloatingPoint() &&
2827 I.getType() == I.getOperand(1)->getType() &&
2828 I.getType() == I.getOperand(2)->getType()) {
2829 SDOperand LHS = getValue(I.getOperand(1));
2830 SDOperand RHS = getValue(I.getOperand(2));
2831 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2832 LHS, RHS));
2833 return;
2834 }
2835 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002836 if (I.getNumOperands() == 2 && // Basic sanity checks.
2837 I.getOperand(1)->getType()->isFloatingPoint() &&
2838 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002839 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002840 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2841 return;
2842 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002843 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002844 if (I.getNumOperands() == 2 && // Basic sanity checks.
2845 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002846 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002847 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002848 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2849 return;
2850 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002851 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002852 if (I.getNumOperands() == 2 && // Basic sanity checks.
2853 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002854 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002855 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002856 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2857 return;
2858 }
2859 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002860 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002861 } else if (isa<InlineAsm>(I.getOperand(0))) {
2862 visitInlineAsm(I);
2863 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002864 }
Misha Brukman835702a2005-04-21 22:36:52 +00002865
Chris Lattner18d2b342005-01-08 22:48:57 +00002866 SDOperand Callee;
2867 if (!RenameFn)
2868 Callee = getValue(I.getOperand(0));
2869 else
2870 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002871
Jim Laskey31fef782007-02-23 21:45:01 +00002872 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002873 I.getCallingConv(),
2874 I.isTailCall(),
2875 Callee,
2876 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002877}
2878
Jim Laskey504e9942007-02-22 15:38:06 +00002879
Chris Lattner6f87d182006-02-22 22:37:12 +00002880SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002881 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002882 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2883 Chain = Val.getValue(1);
2884 Flag = Val.getValue(2);
2885
2886 // If the result was expanded, copy from the top part.
2887 if (Regs.size() > 1) {
2888 assert(Regs.size() == 2 &&
2889 "Cannot expand to more than 2 elts yet!");
2890 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002891 Chain = Hi.getValue(1);
2892 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002893 if (DAG.getTargetLoweringInfo().isLittleEndian())
2894 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2895 else
2896 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002897 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002898
Chris Lattner705948d2006-06-08 18:22:48 +00002899 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002900 // appropriate type.
2901 if (RegVT == ValueVT)
2902 return Val;
2903
Chris Lattner77f04792007-03-25 05:00:54 +00002904 if (MVT::isVector(RegVT)) {
2905 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2906 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2907 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2908 MVT::i32),
2909 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2910 }
2911
Chris Lattner705948d2006-06-08 18:22:48 +00002912 if (MVT::isInteger(RegVT)) {
2913 if (ValueVT < RegVT)
2914 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2915 else
2916 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002917 }
Chris Lattner77f04792007-03-25 05:00:54 +00002918
2919 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2920 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002921}
2922
Chris Lattner571d9642006-02-23 19:21:04 +00002923/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2924/// specified value into the registers specified by this object. This uses
2925/// Chain/Flag as the input and updates them for the output Chain/Flag.
2926void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002927 SDOperand &Chain, SDOperand &Flag,
2928 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002929 if (Regs.size() == 1) {
2930 // If there is a single register and the types differ, this must be
2931 // a promotion.
2932 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002933 if (MVT::isVector(RegVT)) {
2934 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2935 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002936 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002937 if (RegVT < ValueVT)
2938 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2939 else
2940 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002941 } else if (MVT::isFloatingPoint(RegVT) &&
2942 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002943 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002944 } else if (MVT::getSizeInBits(RegVT) ==
2945 MVT::getSizeInBits(Val.getValueType())) {
2946 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2947 } else {
2948 assert(0 && "Unknown mismatch!");
2949 }
Chris Lattner571d9642006-02-23 19:21:04 +00002950 }
2951 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2952 Flag = Chain.getValue(1);
2953 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002954 std::vector<unsigned> R(Regs);
2955 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2956 std::reverse(R.begin(), R.end());
2957
2958 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002959 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002960 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002961 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002962 Flag = Chain.getValue(1);
2963 }
2964 }
2965}
Chris Lattner6f87d182006-02-22 22:37:12 +00002966
Chris Lattner571d9642006-02-23 19:21:04 +00002967/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2968/// operand list. This adds the code marker and includes the number of
2969/// values added into it.
2970void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002971 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002972 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2973 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002974 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2975 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2976}
Chris Lattner6f87d182006-02-22 22:37:12 +00002977
2978/// isAllocatableRegister - If the specified register is safe to allocate,
2979/// i.e. it isn't a stack pointer or some other special register, return the
2980/// register class for the register. Otherwise, return null.
2981static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002982isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2983 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002984 MVT::ValueType FoundVT = MVT::Other;
2985 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002986 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2987 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002988 MVT::ValueType ThisVT = MVT::Other;
2989
Chris Lattnerb1124f32006-02-22 23:09:03 +00002990 const TargetRegisterClass *RC = *RCI;
2991 // If none of the the value types for this register class are valid, we
2992 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002993 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2994 I != E; ++I) {
2995 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002996 // If we have already found this register in a different register class,
2997 // choose the one with the largest VT specified. For example, on
2998 // PowerPC, we favor f64 register classes over f32.
2999 if (FoundVT == MVT::Other ||
3000 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3001 ThisVT = *I;
3002 break;
3003 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00003004 }
3005 }
3006
Chris Lattnerbec582f2006-04-02 00:24:45 +00003007 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00003008
Chris Lattner6f87d182006-02-22 22:37:12 +00003009 // NOTE: This isn't ideal. In particular, this might allocate the
3010 // frame pointer in functions that need it (due to them not being taken
3011 // out of allocation, because a variable sized allocation hasn't been seen
3012 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003013 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3014 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00003015 if (*I == Reg) {
3016 // We found a matching register class. Keep looking at others in case
3017 // we find one with larger registers that this physreg is also in.
3018 FoundRC = RC;
3019 FoundVT = ThisVT;
3020 break;
3021 }
Chris Lattner1558fc62006-02-01 18:59:47 +00003022 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00003023 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00003024}
3025
Chris Lattner1558fc62006-02-01 18:59:47 +00003026
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003027namespace {
3028/// AsmOperandInfo - This contains information for each constraint that we are
3029/// lowering.
3030struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3031 /// ConstraintCode - This contains the actual string for the code, like "m".
3032 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003033
3034 /// ConstraintType - Information about the constraint code, e.g. Register,
3035 /// RegisterClass, Memory, Other, Unknown.
3036 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003037
3038 /// CallOperand/CallOperandval - If this is the result output operand or a
3039 /// clobber, this is null, otherwise it is the incoming operand to the
3040 /// CallInst. This gets modified as the asm is processed.
3041 SDOperand CallOperand;
3042 Value *CallOperandVal;
3043
3044 /// ConstraintVT - The ValueType for the operand value.
3045 MVT::ValueType ConstraintVT;
3046
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003047 /// AssignedRegs - If this is a register or register class operand, this
3048 /// contains the set of register corresponding to the operand.
3049 RegsForValue AssignedRegs;
3050
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003051 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00003052 : InlineAsm::ConstraintInfo(info),
3053 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003054 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3055 }
Chris Lattneref073322007-04-30 17:16:27 +00003056
3057 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003058
3059 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3060 /// busy in OutputRegs/InputRegs.
3061 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3062 std::set<unsigned> &OutputRegs,
3063 std::set<unsigned> &InputRegs) const {
3064 if (isOutReg)
3065 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3066 if (isInReg)
3067 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3068 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003069};
3070} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003071
Chris Lattneref073322007-04-30 17:16:27 +00003072/// getConstraintGenerality - Return an integer indicating how general CT is.
3073static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3074 switch (CT) {
3075 default: assert(0 && "Unknown constraint type!");
3076 case TargetLowering::C_Other:
3077 case TargetLowering::C_Unknown:
3078 return 0;
3079 case TargetLowering::C_Register:
3080 return 1;
3081 case TargetLowering::C_RegisterClass:
3082 return 2;
3083 case TargetLowering::C_Memory:
3084 return 3;
3085 }
3086}
3087
3088void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3089 assert(!Codes.empty() && "Must have at least one constraint");
3090
3091 std::string *Current = &Codes[0];
3092 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3093 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3094 ConstraintCode = *Current;
3095 ConstraintType = CurType;
3096 return;
3097 }
3098
3099 unsigned CurGenerality = getConstraintGenerality(CurType);
3100
3101 // If we have multiple constraints, try to pick the most general one ahead
3102 // of time. This isn't a wonderful solution, but handles common cases.
3103 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3104 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3105 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3106 if (ThisGenerality > CurGenerality) {
3107 // This constraint letter is more general than the previous one,
3108 // use it.
3109 CurType = ThisType;
3110 Current = &Codes[j];
3111 CurGenerality = ThisGenerality;
3112 }
3113 }
3114
3115 ConstraintCode = *Current;
3116 ConstraintType = CurType;
3117}
3118
3119
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003120void SelectionDAGLowering::
3121GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003122 std::set<unsigned> &OutputRegs,
3123 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003124 // Compute whether this value requires an input register, an output register,
3125 // or both.
3126 bool isOutReg = false;
3127 bool isInReg = false;
3128 switch (OpInfo.Type) {
3129 case InlineAsm::isOutput:
3130 isOutReg = true;
3131
3132 // If this is an early-clobber output, or if there is an input
3133 // constraint that matches this, we need to reserve the input register
3134 // so no other inputs allocate to it.
3135 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3136 break;
3137 case InlineAsm::isInput:
3138 isInReg = true;
3139 isOutReg = false;
3140 break;
3141 case InlineAsm::isClobber:
3142 isOutReg = true;
3143 isInReg = true;
3144 break;
3145 }
3146
3147
3148 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003149 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003150
3151 // If this is a constraint for a single physreg, or a constraint for a
3152 // register class, find it.
3153 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3154 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3155 OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003156
3157 unsigned NumRegs = 1;
3158 if (OpInfo.ConstraintVT != MVT::Other)
3159 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3160 MVT::ValueType RegVT;
3161 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3162
Chris Lattner4333f8b2007-04-30 17:29:31 +00003163
3164 // If this is a constraint for a specific physical register, like {r17},
3165 // assign it now.
3166 if (PhysReg.first) {
3167 if (OpInfo.ConstraintVT == MVT::Other)
3168 ValueVT = *PhysReg.second->vt_begin();
3169
3170 // Get the actual register value type. This is important, because the user
3171 // may have asked for (e.g.) the AX register in i32 type. We need to
3172 // remember that AX is actually i16 to get the right extension.
3173 RegVT = *PhysReg.second->vt_begin();
3174
3175 // This is a explicit reference to a physical register.
3176 Regs.push_back(PhysReg.first);
3177
3178 // If this is an expanded reference, add the rest of the regs to Regs.
3179 if (NumRegs != 1) {
3180 TargetRegisterClass::iterator I = PhysReg.second->begin();
3181 TargetRegisterClass::iterator E = PhysReg.second->end();
3182 for (; *I != PhysReg.first; ++I)
3183 assert(I != E && "Didn't find reg!");
3184
3185 // Already added the first reg.
3186 --NumRegs; ++I;
3187 for (; NumRegs; --NumRegs, ++I) {
3188 assert(I != E && "Ran out of registers to allocate!");
3189 Regs.push_back(*I);
3190 }
3191 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003192 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3193 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3194 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003195 }
3196
3197 // Otherwise, if this was a reference to an LLVM register class, create vregs
3198 // for this reference.
3199 std::vector<unsigned> RegClassRegs;
3200 if (PhysReg.second) {
3201 // If this is an early clobber or tied register, our regalloc doesn't know
3202 // how to maintain the constraint. If it isn't, go ahead and create vreg
3203 // and let the regalloc do the right thing.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003204 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3205 // If there is some other early clobber and this is an input register,
3206 // then we are forced to pre-allocate the input reg so it doesn't
3207 // conflict with the earlyclobber.
3208 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003209 RegVT = *PhysReg.second->vt_begin();
3210
3211 if (OpInfo.ConstraintVT == MVT::Other)
3212 ValueVT = RegVT;
3213
3214 // Create the appropriate number of virtual registers.
3215 SSARegMap *RegMap = MF.getSSARegMap();
3216 for (; NumRegs; --NumRegs)
3217 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3218
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003219 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3220 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3221 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003222 }
3223
3224 // Otherwise, we can't allocate it. Let the code below figure out how to
3225 // maintain these constraints.
3226 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3227
3228 } else {
3229 // This is a reference to a register class that doesn't directly correspond
3230 // to an LLVM register class. Allocate NumRegs consecutive, available,
3231 // registers from the class.
3232 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3233 OpInfo.ConstraintVT);
3234 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003235
Chris Lattner4333f8b2007-04-30 17:29:31 +00003236 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3237 unsigned NumAllocated = 0;
3238 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3239 unsigned Reg = RegClassRegs[i];
3240 // See if this register is available.
3241 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3242 (isInReg && InputRegs.count(Reg))) { // Already used.
3243 // Make sure we find consecutive registers.
3244 NumAllocated = 0;
3245 continue;
3246 }
3247
3248 // Check to see if this register is allocatable (i.e. don't give out the
3249 // stack pointer).
3250 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3251 if (!RC) {
3252 // Make sure we find consecutive registers.
3253 NumAllocated = 0;
3254 continue;
3255 }
3256
3257 // Okay, this register is good, we can use it.
3258 ++NumAllocated;
3259
3260 // If we allocated enough consecutive registers, succeed.
3261 if (NumAllocated == NumRegs) {
3262 unsigned RegStart = (i-NumAllocated)+1;
3263 unsigned RegEnd = i+1;
3264 // Mark all of the allocated registers used.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003265 for (unsigned i = RegStart; i != RegEnd; ++i)
3266 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003267
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003268 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3269 OpInfo.ConstraintVT);
3270 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3271 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003272 }
3273 }
3274
3275 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003276 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003277}
3278
3279
Chris Lattner476e67b2006-01-26 22:24:51 +00003280/// visitInlineAsm - Handle a call to an InlineAsm object.
3281///
3282void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3283 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003284
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003285 /// ConstraintOperands - Information about all of the constraints.
3286 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003287
3288 SDOperand Chain = getRoot();
3289 SDOperand Flag;
3290
Chris Lattner1558fc62006-02-01 18:59:47 +00003291 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003292
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003293 // Do a prepass over the constraints, canonicalizing them, and building up the
3294 // ConstraintOperands list.
3295 std::vector<InlineAsm::ConstraintInfo>
3296 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003297
3298 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3299 // constraint. If so, we can't let the register allocator allocate any input
3300 // registers, because it will not know to avoid the earlyclobbered output reg.
3301 bool SawEarlyClobber = false;
3302
3303 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003304 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3305 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3306 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3307
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003308 MVT::ValueType OpVT = MVT::Other;
3309
3310 // Compute the value type for each operand.
3311 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003312 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003313 if (!OpInfo.isIndirect) {
3314 // The return value of the call is this value. As such, there is no
3315 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003316 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3317 OpVT = TLI.getValueType(I.getType());
3318 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003319 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003320 }
3321 break;
3322 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003323 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003324 break;
3325 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003326 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003327 break;
3328 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003329
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003330 // If this is an input or an indirect output, process the call argument.
3331 if (OpInfo.CallOperandVal) {
3332 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3333 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003334 // If this is an indirect operand, the operand is a pointer to the
3335 // accessed type.
3336 if (OpInfo.isIndirect)
3337 OpTy = cast<PointerType>(OpTy)->getElementType();
3338
3339 // If OpTy is not a first-class value, it may be a struct/union that we
3340 // can tile with integers.
3341 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3342 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3343 switch (BitSize) {
3344 default: break;
3345 case 1:
3346 case 8:
3347 case 16:
3348 case 32:
3349 case 64:
3350 OpTy = IntegerType::get(BitSize);
3351 break;
3352 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003353 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003354
3355 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003356 }
3357
3358 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003359
Chris Lattneref073322007-04-30 17:16:27 +00003360 // Compute the constraint code and ConstraintType to use.
3361 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003362
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003363 // Keep track of whether we see an earlyclobber.
3364 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003365
3366 // If this is a memory input, and if the operand is not indirect, do what we
3367 // need to to provide an address for the memory input.
3368 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3369 !OpInfo.isIndirect) {
3370 assert(OpInfo.Type == InlineAsm::isInput &&
3371 "Can only indirectify direct input operands!");
3372
3373 // Memory operands really want the address of the value. If we don't have
3374 // an indirect input, put it in the constpool if we can, otherwise spill
3375 // it to a stack slot.
3376
3377 // If the operand is a float, integer, or vector constant, spill to a
3378 // constant pool entry to get its address.
3379 Value *OpVal = OpInfo.CallOperandVal;
3380 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3381 isa<ConstantVector>(OpVal)) {
3382 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3383 TLI.getPointerTy());
3384 } else {
3385 // Otherwise, create a stack slot and emit a store to it before the
3386 // asm.
3387 const Type *Ty = OpVal->getType();
3388 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3389 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3390 MachineFunction &MF = DAG.getMachineFunction();
3391 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3392 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3393 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3394 OpInfo.CallOperand = StackSlot;
3395 }
3396
3397 // There is no longer a Value* corresponding to this operand.
3398 OpInfo.CallOperandVal = 0;
3399 // It is now an indirect operand.
3400 OpInfo.isIndirect = true;
3401 }
3402
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003403 // If this constraint is for a specific register, allocate it before
3404 // anything else.
3405 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3406 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003407 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003408 ConstraintInfos.clear();
3409
3410
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003411 // Second pass - Loop over all of the operands, assigning virtual or physregs
3412 // to registerclass operands.
3413 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3414 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3415
3416 // C_Register operands have already been allocated, Other/Memory don't need
3417 // to be.
3418 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3419 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3420 }
3421
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003422 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3423 std::vector<SDOperand> AsmNodeOperands;
3424 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3425 AsmNodeOperands.push_back(
3426 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3427
Chris Lattner3a5ed552006-02-01 01:28:23 +00003428
Chris Lattner5c79f982006-02-21 23:12:12 +00003429 // Loop over all of the inputs, copying the operand values into the
3430 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003431 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003432
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003433 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3434 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3435
3436 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3437 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003438
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003439 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003440 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003441 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3442 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003443 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003444 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003445
Chris Lattner9fed5b62006-02-27 23:45:39 +00003446 // Add information to the INLINEASM node to know about this output.
3447 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003448 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3449 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003450 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003451 break;
3452 }
3453
Chris Lattnerb2e55562007-04-28 21:01:43 +00003454 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003455
Chris Lattner6f87d182006-02-22 22:37:12 +00003456 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003457 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003458 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003459 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003460 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003461 exit(1);
3462 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003463
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003464 if (!OpInfo.isIndirect) {
3465 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003466 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003467 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003468 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003469 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003470 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003471 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003472 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003473 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003474
3475 // Add information to the INLINEASM node to know that this register is
3476 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003477 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3478 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003479 break;
3480 }
3481 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003482 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003483
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003484 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003485 // If this is required to match an output register we have already set,
3486 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003487 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003488
Chris Lattner571d9642006-02-23 19:21:04 +00003489 // Scan until we find the definition we already emitted of this operand.
3490 // When we find it, create a RegsForValue operand.
3491 unsigned CurOp = 2; // The first operand.
3492 for (; OperandNo; --OperandNo) {
3493 // Advance to the next operand.
3494 unsigned NumOps =
3495 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003496 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3497 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003498 "Skipped past definitions?");
3499 CurOp += (NumOps>>3)+1;
3500 }
3501
3502 unsigned NumOps =
3503 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003504 if ((NumOps & 7) == 2 /*REGDEF*/) {
3505 // Add NumOps>>3 registers to MatchedRegs.
3506 RegsForValue MatchedRegs;
3507 MatchedRegs.ValueVT = InOperandVal.getValueType();
3508 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3509 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3510 unsigned Reg =
3511 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3512 MatchedRegs.Regs.push_back(Reg);
3513 }
Chris Lattner571d9642006-02-23 19:21:04 +00003514
Chris Lattnere3eeb242007-02-01 01:21:12 +00003515 // Use the produced MatchedRegs object to
3516 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3517 TLI.getPointerTy());
3518 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3519 break;
3520 } else {
3521 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3522 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003523 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003524 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003525
Chris Lattnerb2e55562007-04-28 21:01:43 +00003526 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003527 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003528 "Don't know how to handle indirect other inputs yet!");
3529
Chris Lattner6f043b92006-10-31 19:41:18 +00003530 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003531 OpInfo.ConstraintCode[0],
3532 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003533 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003534 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003535 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003536 exit(1);
3537 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003538
3539 // Add information to the INLINEASM node to know about this input.
3540 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003541 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3542 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003543 AsmNodeOperands.push_back(InOperandVal);
3544 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003545 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003546 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003547 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3548 "Memory operands expect pointer values");
3549
Chris Lattner7ef7a642006-02-24 01:11:24 +00003550 // Add information to the INLINEASM node to know about this input.
3551 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003552 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3553 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003554 AsmNodeOperands.push_back(InOperandVal);
3555 break;
3556 }
3557
Chris Lattnerb2e55562007-04-28 21:01:43 +00003558 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3559 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3560 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003561 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003562 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003563
3564 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003565 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3566 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003567
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003568 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3569 TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003570
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003571 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3572 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003573 break;
3574 }
Chris Lattner571d9642006-02-23 19:21:04 +00003575 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003576 // Add the clobbered value to the operand list, so that the register
3577 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003578 if (!OpInfo.AssignedRegs.Regs.empty())
3579 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3580 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003581 break;
3582 }
Chris Lattner571d9642006-02-23 19:21:04 +00003583 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003584 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003585
3586 // Finish up input operands.
3587 AsmNodeOperands[0] = Chain;
3588 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3589
Chris Lattnerbd887772006-08-14 23:53:35 +00003590 Chain = DAG.getNode(ISD::INLINEASM,
3591 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003592 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003593 Flag = Chain.getValue(1);
3594
Chris Lattner2e56e892006-01-31 02:03:41 +00003595 // If this asm returns a register value, copy the result from that register
3596 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003597 if (!RetValRegs.Regs.empty()) {
3598 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3599
3600 // If the result of the inline asm is a vector, it may have the wrong
3601 // width/num elts. Make sure to convert it to the right type with
3602 // vbit_convert.
3603 if (Val.getValueType() == MVT::Vector) {
3604 const VectorType *VTy = cast<VectorType>(I.getType());
3605 unsigned DesiredNumElts = VTy->getNumElements();
3606 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3607
3608 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3609 DAG.getConstant(DesiredNumElts, MVT::i32),
3610 DAG.getValueType(DesiredEltVT));
3611 }
3612
3613 setValue(&I, Val);
3614 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003615
Chris Lattner2e56e892006-01-31 02:03:41 +00003616 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3617
3618 // Process indirect outputs, first output all of the flagged copies out of
3619 // physregs.
3620 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003621 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003622 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003623 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3624 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003625 }
3626
3627 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003628 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003629 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003630 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003631 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003632 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003633 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003634 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3635 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003636 DAG.setRoot(Chain);
3637}
3638
3639
Chris Lattner7a60d912005-01-07 07:47:53 +00003640void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3641 SDOperand Src = getValue(I.getOperand(0));
3642
3643 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003644
3645 if (IntPtr < Src.getValueType())
3646 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3647 else if (IntPtr > Src.getValueType())
3648 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003649
3650 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003651 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003652 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3653 Src, getIntPtrConstant(ElementSize));
3654
Reid Spencere63b6512006-12-31 05:55:36 +00003655 TargetLowering::ArgListTy Args;
3656 TargetLowering::ArgListEntry Entry;
3657 Entry.Node = Src;
3658 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003659 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003660
3661 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003662 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003663 DAG.getExternalSymbol("malloc", IntPtr),
3664 Args, DAG);
3665 setValue(&I, Result.first); // Pointers always fit in registers
3666 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003667}
3668
3669void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003670 TargetLowering::ArgListTy Args;
3671 TargetLowering::ArgListEntry Entry;
3672 Entry.Node = getValue(I.getOperand(0));
3673 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003674 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003675 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003676 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003677 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003678 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3679 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003680}
3681
Chris Lattner13d7c252005-08-26 20:54:47 +00003682// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3683// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3684// instructions are special in various ways, which require special support to
3685// insert. The specified MachineInstr is created but not inserted into any
3686// basic blocks, and the scheduler passes ownership of it to this method.
3687MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3688 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003689 cerr << "If a target marks an instruction with "
3690 << "'usesCustomDAGSchedInserter', it must implement "
3691 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003692 abort();
3693 return 0;
3694}
3695
Chris Lattner58cfd792005-01-09 00:00:49 +00003696void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003697 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3698 getValue(I.getOperand(1)),
3699 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003700}
3701
3702void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003703 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3704 getValue(I.getOperand(0)),
3705 DAG.getSrcValue(I.getOperand(0)));
3706 setValue(&I, V);
3707 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003708}
3709
3710void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003711 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3712 getValue(I.getOperand(1)),
3713 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003714}
3715
3716void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003717 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3718 getValue(I.getOperand(1)),
3719 getValue(I.getOperand(2)),
3720 DAG.getSrcValue(I.getOperand(1)),
3721 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003722}
3723
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003724/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3725/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3726static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3727 unsigned &i, SelectionDAG &DAG,
3728 TargetLowering &TLI) {
3729 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3730 return SDOperand(Arg, i++);
3731
3732 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3733 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3734 if (NumVals == 1) {
3735 return DAG.getNode(ISD::BIT_CONVERT, VT,
3736 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3737 } else if (NumVals == 2) {
3738 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3739 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3740 if (!TLI.isLittleEndian())
3741 std::swap(Lo, Hi);
3742 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3743 } else {
3744 // Value scalarized into many values. Unimp for now.
3745 assert(0 && "Cannot expand i64 -> i16 yet!");
3746 }
3747 return SDOperand();
3748}
3749
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003750/// TargetLowering::LowerArguments - This is the default LowerArguments
3751/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003752/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3753/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003754std::vector<SDOperand>
3755TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003756 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003757 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003758 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3759 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003760 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003761 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3762 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3763
3764 // Add one result value for each formal argument.
3765 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003766 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003767 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3768 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003769 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003770 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003771 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003772 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003773
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003774 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3775 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003776 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003777 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003778 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003779 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003780 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003781 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003782 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003783 Flags |= ISD::ParamFlags::StructReturn;
3784 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003785
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003786 switch (getTypeAction(VT)) {
3787 default: assert(0 && "Unknown type action!");
3788 case Legal:
3789 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003790 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003791 break;
3792 case Promote:
3793 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003794 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003795 break;
3796 case Expand:
3797 if (VT != MVT::Vector) {
3798 // If this is a large integer, it needs to be broken up into small
3799 // integers. Figure out what the destination type is and how many small
3800 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003801 MVT::ValueType NVT = getTypeToExpandTo(VT);
3802 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003803 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003804 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003805 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003806 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003807 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3808 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003809 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3810 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003811 } else {
3812 // Otherwise, this is a vector type. We only support legal vectors
3813 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003814 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3815 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003816
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003817 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003818 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003819 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3820 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3821 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003822 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003823 } else {
3824 assert(0 && "Don't support illegal by-val vector arguments yet!");
3825 }
3826 }
3827 break;
3828 }
3829 }
Evan Cheng9618df12006-04-25 23:03:35 +00003830
Chris Lattner3d826992006-05-16 06:45:34 +00003831 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003832
3833 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003834 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3835 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003836 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003837
3838 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003839
3840 // Set up the return result vector.
3841 Ops.clear();
3842 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003843 unsigned Idx = 1;
3844 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3845 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003846 MVT::ValueType VT = getValueType(I->getType());
3847
3848 switch (getTypeAction(VT)) {
3849 default: assert(0 && "Unknown type action!");
3850 case Legal:
3851 Ops.push_back(SDOperand(Result, i++));
3852 break;
3853 case Promote: {
3854 SDOperand Op(Result, i++);
3855 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003856 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003857 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3858 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003859 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003860 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3861 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003862 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3863 } else {
3864 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3865 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3866 }
3867 Ops.push_back(Op);
3868 break;
3869 }
3870 case Expand:
3871 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003872 // If this is a large integer or a floating point node that needs to be
3873 // expanded, it needs to be reassembled from small integers. Figure out
3874 // what the source elt type is and how many small integers it is.
3875 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003876 } else {
3877 // Otherwise, this is a vector type. We only support legal vectors
3878 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003879 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003880 unsigned NumElems = PTy->getNumElements();
3881 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003882
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003883 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003884 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003885 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003886 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003887 SDOperand N = SDOperand(Result, i++);
3888 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003889 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3890 DAG.getConstant(NumElems, MVT::i32),
3891 DAG.getValueType(getValueType(EltTy)));
3892 Ops.push_back(N);
3893 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003894 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003895 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003896 }
3897 }
3898 break;
3899 }
3900 }
3901 return Ops;
3902}
3903
Chris Lattneraaa23d92006-05-16 22:53:20 +00003904
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003905/// ExpandScalarCallArgs - Recursively expand call argument node by
3906/// bit_converting it or extract a pair of elements from the larger node.
3907static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003908 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003909 SmallVector<SDOperand, 32> &Ops,
3910 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003911 TargetLowering &TLI,
3912 bool isFirst = true) {
3913
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003914 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003915 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003916 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003917 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3918 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003919 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003920 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003921 return;
3922 }
3923
3924 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3925 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3926 if (NumVals == 1) {
3927 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003928 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003929 } else if (NumVals == 2) {
3930 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3931 DAG.getConstant(0, TLI.getPointerTy()));
3932 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3933 DAG.getConstant(1, TLI.getPointerTy()));
3934 if (!TLI.isLittleEndian())
3935 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003936 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3937 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003938 } else {
3939 // Value scalarized into many values. Unimp for now.
3940 assert(0 && "Cannot expand i64 -> i16 yet!");
3941 }
3942}
3943
Chris Lattneraaa23d92006-05-16 22:53:20 +00003944/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3945/// implementation, which just inserts an ISD::CALL node, which is later custom
3946/// lowered by the target to something concrete. FIXME: When all targets are
3947/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3948std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003949TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3950 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003951 unsigned CallingConv, bool isTailCall,
3952 SDOperand Callee,
3953 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003954 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003955 Ops.push_back(Chain); // Op#0 - Chain
3956 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3957 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3958 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3959 Ops.push_back(Callee);
3960
3961 // Handle all of the outgoing arguments.
3962 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003963 MVT::ValueType VT = getValueType(Args[i].Ty);
3964 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003965 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003966 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003967 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003968
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003969 if (Args[i].isSExt)
3970 Flags |= ISD::ParamFlags::SExt;
3971 if (Args[i].isZExt)
3972 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003973 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003974 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003975 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003976 Flags |= ISD::ParamFlags::StructReturn;
3977 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003978
Chris Lattneraaa23d92006-05-16 22:53:20 +00003979 switch (getTypeAction(VT)) {
3980 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003981 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003982 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003983 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003984 break;
3985 case Promote:
3986 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003987 unsigned ExtOp;
3988 if (Args[i].isSExt)
3989 ExtOp = ISD::SIGN_EXTEND;
3990 else if (Args[i].isZExt)
3991 ExtOp = ISD::ZERO_EXTEND;
3992 else
3993 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003994 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3995 } else {
3996 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen9a4d9872007-06-07 21:07:15 +00003997 // A true promotion would change the size of the argument.
3998 // Instead, pretend this is an int. If FP objects are not
3999 // passed the same as ints, the original type should be Legal
4000 // and we should not get here.
4001 Op = DAG.getNode(ISD::BIT_CONVERT,
4002 VT==MVT::f32 ? MVT::i32 :
4003 (VT==MVT::f64 ? MVT::i64 :
4004 MVT::Other),
4005 Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004006 }
4007 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004008 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004009 break;
4010 case Expand:
4011 if (VT != MVT::Vector) {
4012 // If this is a large integer, it needs to be broken down into small
4013 // integers. Figure out what the source elt type is and how many small
4014 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004015 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004016 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004017 // Otherwise, this is a vector type. We only support legal vectors
4018 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004019 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004020 unsigned NumElems = PTy->getNumElements();
4021 const Type *EltTy = PTy->getElementType();
4022
4023 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004024 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00004025 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00004026 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00004027 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00004028 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4029 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004030 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00004031 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004032 assert(0 && "Don't support illegal by-val vector call args yet!");
4033 abort();
4034 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004035 }
4036 break;
4037 }
4038 }
4039
4040 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00004041 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004042
4043 if (RetTy != Type::VoidTy) {
4044 MVT::ValueType VT = getValueType(RetTy);
4045 switch (getTypeAction(VT)) {
4046 default: assert(0 && "Unknown type action!");
4047 case Legal:
4048 RetTys.push_back(VT);
4049 break;
4050 case Promote:
4051 RetTys.push_back(getTypeToTransformTo(VT));
4052 break;
4053 case Expand:
4054 if (VT != MVT::Vector) {
4055 // If this is a large integer, it needs to be reassembled from small
4056 // integers. Figure out what the source elt type is and how many small
4057 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00004058 MVT::ValueType NVT = getTypeToExpandTo(VT);
4059 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004060 for (unsigned i = 0; i != NumVals; ++i)
4061 RetTys.push_back(NVT);
4062 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004063 // Otherwise, this is a vector type. We only support legal vectors
4064 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004065 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004066 unsigned NumElems = PTy->getNumElements();
4067 const Type *EltTy = PTy->getElementType();
4068
4069 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004070 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00004071 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4072 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4073 RetTys.push_back(TVT);
4074 } else {
4075 assert(0 && "Don't support illegal by-val vector call results yet!");
4076 abort();
4077 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004078 }
4079 }
4080 }
4081
4082 RetTys.push_back(MVT::Other); // Always has a chain.
4083
4084 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004085 SDOperand Res = DAG.getNode(ISD::CALL,
4086 DAG.getVTList(&RetTys[0], RetTys.size()),
4087 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004088
4089 // This returns a pair of operands. The first element is the
4090 // return value for the function (if RetTy is not VoidTy). The second
4091 // element is the outgoing token chain.
4092 SDOperand ResVal;
4093 if (RetTys.size() != 1) {
4094 MVT::ValueType VT = getValueType(RetTy);
4095 if (RetTys.size() == 2) {
4096 ResVal = Res;
4097
4098 // If this value was promoted, truncate it down.
4099 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004100 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00004101 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00004102 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004103 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4104 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004105
4106 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004107 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00004108 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004109 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004110 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4111 // "N x PTyElementVT" MVT::Vector type.
4112 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00004113 DAG.getConstant(NumElems, MVT::i32),
4114 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00004115 } else {
4116 abort();
4117 }
4118 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004119 unsigned AssertOp = ISD::AssertSext;
4120 if (!RetTyIsSigned)
4121 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004122 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4123 DAG.getValueType(VT));
4124 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4125 } else {
4126 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004127 if (getTypeAction(VT) == Expand)
4128 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4129 else
4130 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004131 }
4132 }
4133 } else if (RetTys.size() == 3) {
4134 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4135 Res.getValue(0), Res.getValue(1));
4136
4137 } else {
4138 assert(0 && "Case not handled yet!");
4139 }
4140 }
4141
4142 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4143}
4144
Chris Lattner29dcc712005-05-14 05:50:48 +00004145SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004146 assert(0 && "LowerOperation not implemented for this target!");
4147 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004148 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004149}
4150
Nate Begeman595ec732006-01-28 03:14:31 +00004151SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4152 SelectionDAG &DAG) {
4153 assert(0 && "CustomPromoteOperation not implemented for this target!");
4154 abort();
4155 return SDOperand();
4156}
4157
Evan Cheng6781b6e2006-02-15 21:59:04 +00004158/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004159/// operand.
4160static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004161 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004162 MVT::ValueType CurVT = VT;
4163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4164 uint64_t Val = C->getValue() & 255;
4165 unsigned Shift = 8;
4166 while (CurVT != MVT::i8) {
4167 Val = (Val << Shift) | Val;
4168 Shift <<= 1;
4169 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004170 }
4171 return DAG.getConstant(Val, VT);
4172 } else {
4173 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4174 unsigned Shift = 8;
4175 while (CurVT != MVT::i8) {
4176 Value =
4177 DAG.getNode(ISD::OR, VT,
4178 DAG.getNode(ISD::SHL, VT, Value,
4179 DAG.getConstant(Shift, MVT::i8)), Value);
4180 Shift <<= 1;
4181 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004182 }
4183
4184 return Value;
4185 }
4186}
4187
Evan Cheng6781b6e2006-02-15 21:59:04 +00004188/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4189/// used when a memcpy is turned into a memset when the source is a constant
4190/// string ptr.
4191static SDOperand getMemsetStringVal(MVT::ValueType VT,
4192 SelectionDAG &DAG, TargetLowering &TLI,
4193 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004194 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004195 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004196 if (TLI.isLittleEndian())
4197 Offset = Offset + MSB - 1;
4198 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004199 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004200 Offset += TLI.isLittleEndian() ? -1 : 1;
4201 }
4202 return DAG.getConstant(Val, VT);
4203}
4204
Evan Cheng81fcea82006-02-14 08:22:34 +00004205/// getMemBasePlusOffset - Returns base and offset node for the
4206static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4207 SelectionDAG &DAG, TargetLowering &TLI) {
4208 MVT::ValueType VT = Base.getValueType();
4209 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4210}
4211
Evan Chengdb2a7a72006-02-14 20:12:38 +00004212/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004213/// to replace the memset / memcpy is below the threshold. It also returns the
4214/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004215static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4216 unsigned Limit, uint64_t Size,
4217 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004218 MVT::ValueType VT;
4219
4220 if (TLI.allowsUnalignedMemoryAccesses()) {
4221 VT = MVT::i64;
4222 } else {
4223 switch (Align & 7) {
4224 case 0:
4225 VT = MVT::i64;
4226 break;
4227 case 4:
4228 VT = MVT::i32;
4229 break;
4230 case 2:
4231 VT = MVT::i16;
4232 break;
4233 default:
4234 VT = MVT::i8;
4235 break;
4236 }
4237 }
4238
Evan Chengd5026102006-02-14 09:11:59 +00004239 MVT::ValueType LVT = MVT::i64;
4240 while (!TLI.isTypeLegal(LVT))
4241 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4242 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004243
Evan Chengd5026102006-02-14 09:11:59 +00004244 if (VT > LVT)
4245 VT = LVT;
4246
Evan Cheng04514992006-02-14 23:05:54 +00004247 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004248 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004249 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004250 while (VTSize > Size) {
4251 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004252 VTSize >>= 1;
4253 }
Evan Chengd5026102006-02-14 09:11:59 +00004254 assert(MVT::isInteger(VT));
4255
4256 if (++NumMemOps > Limit)
4257 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004258 MemOps.push_back(VT);
4259 Size -= VTSize;
4260 }
Evan Chengd5026102006-02-14 09:11:59 +00004261
4262 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004263}
4264
Chris Lattner875def92005-01-11 05:56:49 +00004265void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004266 SDOperand Op1 = getValue(I.getOperand(1));
4267 SDOperand Op2 = getValue(I.getOperand(2));
4268 SDOperand Op3 = getValue(I.getOperand(3));
4269 SDOperand Op4 = getValue(I.getOperand(4));
4270 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4271 if (Align == 0) Align = 1;
4272
4273 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4274 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004275
4276 // Expand memset / memcpy to a series of load / store ops
4277 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004278 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004279 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004280 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004281 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004282 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4283 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004284 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004285 unsigned Offset = 0;
4286 for (unsigned i = 0; i < NumMemOps; i++) {
4287 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004288 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004289 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004290 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004291 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004292 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004293 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004294 Offset += VTSize;
4295 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004296 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004297 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004298 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004299 case ISD::MEMCPY: {
4300 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4301 Size->getValue(), Align, TLI)) {
4302 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004303 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004304 GlobalAddressSDNode *G = NULL;
4305 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004306 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004307
4308 if (Op2.getOpcode() == ISD::GlobalAddress)
4309 G = cast<GlobalAddressSDNode>(Op2);
4310 else if (Op2.getOpcode() == ISD::ADD &&
4311 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4312 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4313 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004314 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004315 }
4316 if (G) {
4317 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004318 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004319 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004320 if (!Str.empty()) {
4321 CopyFromStr = true;
4322 SrcOff += SrcDelta;
4323 }
4324 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004325 }
4326
Evan Chenge2038bd2006-02-15 01:54:51 +00004327 for (unsigned i = 0; i < NumMemOps; i++) {
4328 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004329 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004330 SDOperand Value, Chain, Store;
4331
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004332 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004333 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4334 Chain = getRoot();
4335 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004336 DAG.getStore(Chain, Value,
4337 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004338 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004339 } else {
4340 Value = DAG.getLoad(VT, getRoot(),
4341 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004342 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004343 Chain = Value.getValue(1);
4344 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004345 DAG.getStore(Chain, Value,
4346 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004347 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004348 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004349 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004350 SrcOff += VTSize;
4351 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004352 }
4353 }
4354 break;
4355 }
4356 }
4357
4358 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004359 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4360 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004361 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004362 }
4363 }
4364
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004365 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004366}
4367
Chris Lattner875def92005-01-11 05:56:49 +00004368//===----------------------------------------------------------------------===//
4369// SelectionDAGISel code
4370//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004371
4372unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4373 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4374}
4375
Chris Lattnerc9950c12005-08-17 06:37:43 +00004376void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004377 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004378 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004379}
Chris Lattner7a60d912005-01-07 07:47:53 +00004380
Chris Lattner35397782005-12-05 07:10:48 +00004381
Chris Lattnerbba52192006-10-28 19:22:10 +00004382
Chris Lattner7a60d912005-01-07 07:47:53 +00004383bool SelectionDAGISel::runOnFunction(Function &Fn) {
4384 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4385 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004386 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004387
4388 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4389
4390 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Duncan Sands61166502007-06-06 10:05:18 +00004391 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator())) {
4392 // Mark landing pad.
4393 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[Invoke->getSuccessor(1)];
4394 LandingPad->setIsLandingPad();
4395 }
4396
4397 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004398 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004399
Evan Cheng276b44b2007-02-10 02:43:39 +00004400 // Add function live-ins to entry block live-in set.
4401 BasicBlock *EntryBB = &Fn.getEntryBlock();
4402 BB = FuncInfo.MBBMap[EntryBB];
4403 if (!MF.livein_empty())
4404 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4405 E = MF.livein_end(); I != E; ++I)
4406 BB->addLiveIn(I->first);
4407
Chris Lattner7a60d912005-01-07 07:47:53 +00004408 return true;
4409}
4410
Chris Lattnered0110b2006-10-27 21:36:01 +00004411SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4412 unsigned Reg) {
4413 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004414 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004415 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004416 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004417
4418 // If this type is not legal, we must make sure to not create an invalid
4419 // register use.
4420 MVT::ValueType SrcVT = Op.getValueType();
4421 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004422 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004423 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004424 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004425 // Handle copies from generic vectors to registers.
4426 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004427 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004428 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004429
Chris Lattner5fe1f542006-03-31 02:06:56 +00004430 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4431 // MVT::Vector type.
4432 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4433 DAG.getConstant(NE, MVT::i32),
4434 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004435
Chris Lattner5fe1f542006-03-31 02:06:56 +00004436 // Loop over all of the elements of the resultant vector,
4437 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4438 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004439 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004440 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004441 for (unsigned i = 0; i != NE; ++i) {
4442 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004443 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004444 if (PTyElementVT == PTyLegalElementVT) {
4445 // Elements are legal.
4446 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4447 } else if (PTyLegalElementVT > PTyElementVT) {
4448 // Elements are promoted.
4449 if (MVT::isFloatingPoint(PTyLegalElementVT))
4450 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4451 else
4452 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4453 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4454 } else {
4455 // Elements are expanded.
4456 // The src value is expanded into multiple registers.
4457 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004458 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004459 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004460 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004461 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4462 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4463 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004464 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004465 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4466 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004467 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004468 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004469 if (MVT::isFloatingPoint(SrcVT))
4470 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4471 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004472 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004473 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004474 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004475 DestVT = TLI.getTypeToExpandTo(SrcVT);
4476 unsigned NumVals = TLI.getNumElements(SrcVT);
4477 if (NumVals == 1)
4478 return DAG.getCopyToReg(getRoot(), Reg,
4479 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4480 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004481 // The src value is expanded into multiple registers.
4482 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004483 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004484 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004485 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004486 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004487 return DAG.getCopyToReg(Op, Reg+1, Hi);
4488 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004489}
4490
Chris Lattner16f64df2005-01-17 17:15:02 +00004491void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004492LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004493 std::vector<SDOperand> &UnorderedChains) {
4494 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004495 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004496 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004497 SDOperand OldRoot = SDL.DAG.getRoot();
4498 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004499
Chris Lattner6871b232005-10-30 19:42:35 +00004500 unsigned a = 0;
4501 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4502 AI != E; ++AI, ++a)
4503 if (!AI->use_empty()) {
4504 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004505
Chris Lattner6871b232005-10-30 19:42:35 +00004506 // If this argument is live outside of the entry block, insert a copy from
4507 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004508 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4509 if (VMI != FuncInfo.ValueMap.end()) {
4510 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004511 UnorderedChains.push_back(Copy);
4512 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004513 }
Chris Lattner6871b232005-10-30 19:42:35 +00004514
Chris Lattner6871b232005-10-30 19:42:35 +00004515 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004516 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004517 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004518}
4519
Chris Lattner7a60d912005-01-07 07:47:53 +00004520void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4521 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004522 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004523 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004524
4525 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004526
Chris Lattner6871b232005-10-30 19:42:35 +00004527 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004528 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004529 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004530
4531 BB = FuncInfo.MBBMap[LLVMBB];
4532 SDL.setCurrentBasicBlock(BB);
4533
Duncan Sands61166502007-06-06 10:05:18 +00004534 if (ExceptionHandling && BB->isLandingPad()) {
4535 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4536
4537 if (MMI) {
4538 // Add a label to mark the beginning of the landing pad. Deletion of the
4539 // landing pad can thus be detected via the MachineModuleInfo.
4540 unsigned LabelID = MMI->addLandingPad(BB);
4541 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4542 DAG.getConstant(LabelID, MVT::i32)));
4543 }
4544 }
4545
Chris Lattner7a60d912005-01-07 07:47:53 +00004546 // Lower all of the non-terminator instructions.
4547 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4548 I != E; ++I)
4549 SDL.visit(*I);
Duncan Sands97f72362007-06-13 05:51:31 +00004550
Chris Lattner7a60d912005-01-07 07:47:53 +00004551 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004552 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004553 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004554 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004555 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004556 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004557 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004558 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004559 }
4560
4561 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4562 // ensure constants are generated when needed. Remember the virtual registers
4563 // that need to be added to the Machine PHI nodes as input. We cannot just
4564 // directly add them, because expansion might result in multiple MBB's for one
4565 // BB. As such, the start of the BB might correspond to a different MBB than
4566 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004567 //
Chris Lattner84a03502006-10-27 23:50:33 +00004568 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004569
4570 // Emit constants only once even if used by multiple PHI nodes.
4571 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004572
Chris Lattner84a03502006-10-27 23:50:33 +00004573 // Vector bool would be better, but vector<bool> is really slow.
4574 std::vector<unsigned char> SuccsHandled;
4575 if (TI->getNumSuccessors())
4576 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4577
Chris Lattner7a60d912005-01-07 07:47:53 +00004578 // Check successor nodes PHI nodes that expect a constant to be available from
4579 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004580 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4581 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004582 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004583 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004584
Chris Lattner84a03502006-10-27 23:50:33 +00004585 // If this terminator has multiple identical successors (common for
4586 // switches), only handle each succ once.
4587 unsigned SuccMBBNo = SuccMBB->getNumber();
4588 if (SuccsHandled[SuccMBBNo]) continue;
4589 SuccsHandled[SuccMBBNo] = true;
4590
4591 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004592 PHINode *PN;
4593
4594 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4595 // nodes and Machine PHI nodes, but the incoming operands have not been
4596 // emitted yet.
4597 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004598 (PN = dyn_cast<PHINode>(I)); ++I) {
4599 // Ignore dead phi's.
4600 if (PN->use_empty()) continue;
4601
4602 unsigned Reg;
4603 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004604
Chris Lattner84a03502006-10-27 23:50:33 +00004605 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4606 unsigned &RegOut = ConstantsOut[C];
4607 if (RegOut == 0) {
4608 RegOut = FuncInfo.CreateRegForValue(C);
4609 UnorderedChains.push_back(
4610 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004611 }
Chris Lattner84a03502006-10-27 23:50:33 +00004612 Reg = RegOut;
4613 } else {
4614 Reg = FuncInfo.ValueMap[PHIOp];
4615 if (Reg == 0) {
4616 assert(isa<AllocaInst>(PHIOp) &&
4617 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4618 "Didn't codegen value into a register!??");
4619 Reg = FuncInfo.CreateRegForValue(PHIOp);
4620 UnorderedChains.push_back(
4621 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004622 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004623 }
Chris Lattner84a03502006-10-27 23:50:33 +00004624
4625 // Remember that this register needs to added to the machine PHI node as
4626 // the input for this MBB.
4627 MVT::ValueType VT = TLI.getValueType(PN->getType());
4628 unsigned NumElements;
4629 if (VT != MVT::Vector)
4630 NumElements = TLI.getNumElements(VT);
4631 else {
4632 MVT::ValueType VT1,VT2;
4633 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004634 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004635 VT1, VT2);
4636 }
4637 for (unsigned i = 0, e = NumElements; i != e; ++i)
4638 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4639 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004640 }
4641 ConstantsOut.clear();
4642
Chris Lattner718b5c22005-01-13 17:59:43 +00004643 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004644 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004645 SDOperand Root = SDL.getRoot();
4646 if (Root.getOpcode() != ISD::EntryToken) {
4647 unsigned i = 0, e = UnorderedChains.size();
4648 for (; i != e; ++i) {
4649 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4650 if (UnorderedChains[i].Val->getOperand(0) == Root)
4651 break; // Don't add the root if we already indirectly depend on it.
4652 }
4653
4654 if (i == e)
4655 UnorderedChains.push_back(Root);
4656 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004657 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4658 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004659 }
4660
Chris Lattner7a60d912005-01-07 07:47:53 +00004661 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004662 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004663
Nate Begemaned728c12006-03-27 01:32:24 +00004664 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004665 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004666 SwitchCases.clear();
4667 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004668 JTCases.clear();
4669 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004670 BitTestCases.clear();
4671 BitTestCases = SDL.BitTestCases;
4672
Chris Lattner4108bb02005-01-17 19:43:36 +00004673 // Make sure the root of the DAG is up-to-date.
4674 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004675}
4676
Nate Begemaned728c12006-03-27 01:32:24 +00004677void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004678 // Get alias analysis for load/store combining.
4679 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4680
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004681 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004682 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004683
Bill Wendling22e978a2006-12-07 20:04:42 +00004684 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004685 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004686
Chris Lattner7a60d912005-01-07 07:47:53 +00004687 // Second step, hack on the DAG until it only uses operations and types that
4688 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004689 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004690
Bill Wendling22e978a2006-12-07 20:04:42 +00004691 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004692 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004693
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004694 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004695 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004696
Evan Cheng739a6a42006-01-21 02:32:06 +00004697 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004698
Chris Lattner5ca31d92005-03-30 01:10:47 +00004699 // Third, instruction select all of the operations to machine code, adding the
4700 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004701 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004702
Bill Wendling22e978a2006-12-07 20:04:42 +00004703 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004704 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004705}
Chris Lattner7a60d912005-01-07 07:47:53 +00004706
Nate Begemaned728c12006-03-27 01:32:24 +00004707void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4708 FunctionLoweringInfo &FuncInfo) {
4709 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4710 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004711 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004712 CurDAG = &DAG;
4713
4714 // First step, lower LLVM code to some DAG. This DAG may use operations and
4715 // types that are not supported by the target.
4716 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4717
4718 // Second step, emit the lowered DAG as machine code.
4719 CodeGenAndEmitDAG(DAG);
4720 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004721
4722 DOUT << "Total amount of phi nodes to update: "
4723 << PHINodesToUpdate.size() << "\n";
4724 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4725 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4726 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004727
Chris Lattner5ca31d92005-03-30 01:10:47 +00004728 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004729 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004730 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004731 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4732 MachineInstr *PHI = PHINodesToUpdate[i].first;
4733 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4734 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004735 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004736 PHI->addMachineBasicBlockOperand(BB);
4737 }
4738 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004739 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004740
4741 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4742 // Lower header first, if it wasn't already lowered
4743 if (!BitTestCases[i].Emitted) {
4744 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4745 CurDAG = &HSDAG;
4746 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4747 // Set the current basic block to the mbb we wish to insert the code into
4748 BB = BitTestCases[i].Parent;
4749 HSDL.setCurrentBasicBlock(BB);
4750 // Emit the code
4751 HSDL.visitBitTestHeader(BitTestCases[i]);
4752 HSDAG.setRoot(HSDL.getRoot());
4753 CodeGenAndEmitDAG(HSDAG);
4754 }
4755
4756 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4757 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4758 CurDAG = &BSDAG;
4759 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4760 // Set the current basic block to the mbb we wish to insert the code into
4761 BB = BitTestCases[i].Cases[j].ThisBB;
4762 BSDL.setCurrentBasicBlock(BB);
4763 // Emit the code
4764 if (j+1 != ej)
4765 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4766 BitTestCases[i].Reg,
4767 BitTestCases[i].Cases[j]);
4768 else
4769 BSDL.visitBitTestCase(BitTestCases[i].Default,
4770 BitTestCases[i].Reg,
4771 BitTestCases[i].Cases[j]);
4772
4773
4774 BSDAG.setRoot(BSDL.getRoot());
4775 CodeGenAndEmitDAG(BSDAG);
4776 }
4777
4778 // Update PHI Nodes
4779 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4780 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4781 MachineBasicBlock *PHIBB = PHI->getParent();
4782 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4783 "This is not a machine PHI node that we are updating!");
4784 // This is "default" BB. We have two jumps to it. From "header" BB and
4785 // from last "case" BB.
4786 if (PHIBB == BitTestCases[i].Default) {
4787 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4788 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004789 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004790 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4791 }
4792 // One of "cases" BB.
4793 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4794 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4795 if (cBB->succ_end() !=
4796 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4797 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4798 PHI->addMachineBasicBlockOperand(cBB);
4799 }
4800 }
4801 }
4802 }
4803
Nate Begeman866b4b42006-04-23 06:26:20 +00004804 // If the JumpTable record is filled in, then we need to emit a jump table.
4805 // Updating the PHI nodes is tricky in this case, since we need to determine
4806 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004807 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4808 // Lower header first, if it wasn't already lowered
4809 if (!JTCases[i].first.Emitted) {
4810 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4811 CurDAG = &HSDAG;
4812 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4813 // Set the current basic block to the mbb we wish to insert the code into
4814 BB = JTCases[i].first.HeaderBB;
4815 HSDL.setCurrentBasicBlock(BB);
4816 // Emit the code
4817 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4818 HSDAG.setRoot(HSDL.getRoot());
4819 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004820 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004821
4822 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4823 CurDAG = &JSDAG;
4824 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004825 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004826 BB = JTCases[i].second.MBB;
4827 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004828 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004829 JSDL.visitJumpTable(JTCases[i].second);
4830 JSDAG.setRoot(JSDL.getRoot());
4831 CodeGenAndEmitDAG(JSDAG);
4832
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004833 // Update PHI Nodes
4834 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4835 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4836 MachineBasicBlock *PHIBB = PHI->getParent();
4837 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4838 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004839 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004840 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004841 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004842 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004843 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004844 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004845 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004846 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004847 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004848 }
4849 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004850 }
4851
Chris Lattner76a7bc82006-10-22 23:00:53 +00004852 // If the switch block involved a branch to one of the actual successors, we
4853 // need to update PHI nodes in that block.
4854 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4855 MachineInstr *PHI = PHINodesToUpdate[i].first;
4856 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4857 "This is not a machine PHI node that we are updating!");
4858 if (BB->isSuccessor(PHI->getParent())) {
4859 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4860 PHI->addMachineBasicBlockOperand(BB);
4861 }
4862 }
4863
Nate Begemaned728c12006-03-27 01:32:24 +00004864 // If we generated any switch lowering information, build and codegen any
4865 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004866 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004867 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004868 CurDAG = &SDAG;
4869 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004870
Nate Begemaned728c12006-03-27 01:32:24 +00004871 // Set the current basic block to the mbb we wish to insert the code into
4872 BB = SwitchCases[i].ThisBB;
4873 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004874
Nate Begemaned728c12006-03-27 01:32:24 +00004875 // Emit the code
4876 SDL.visitSwitchCase(SwitchCases[i]);
4877 SDAG.setRoot(SDL.getRoot());
4878 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004879
4880 // Handle any PHI nodes in successors of this chunk, as if we were coming
4881 // from the original BB before switch expansion. Note that PHI nodes can
4882 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4883 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004884 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004885 for (MachineBasicBlock::iterator Phi = BB->begin();
4886 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4887 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4888 for (unsigned pn = 0; ; ++pn) {
4889 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4890 if (PHINodesToUpdate[pn].first == Phi) {
4891 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4892 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4893 break;
4894 }
4895 }
Nate Begemaned728c12006-03-27 01:32:24 +00004896 }
Chris Lattner707339a52006-09-07 01:59:34 +00004897
4898 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004899 if (BB == SwitchCases[i].FalseBB)
4900 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004901
4902 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004903 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004904 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004905 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004906 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004907 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004908}
Evan Cheng739a6a42006-01-21 02:32:06 +00004909
Jim Laskey95eda5b2006-08-01 14:21:23 +00004910
Evan Cheng739a6a42006-01-21 02:32:06 +00004911//===----------------------------------------------------------------------===//
4912/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4913/// target node in the graph.
4914void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4915 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004916
Jim Laskey29e635d2006-08-02 12:30:23 +00004917 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004918
4919 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004920 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004921 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004922 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004923
Jim Laskey03593f72006-08-01 18:29:48 +00004924 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004925 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004926 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004927}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004928
Chris Lattner47639db2006-03-06 00:22:00 +00004929
Jim Laskey03593f72006-08-01 18:29:48 +00004930HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4931 return new HazardRecognizer();
4932}
4933
Chris Lattner6df34962006-10-11 03:58:02 +00004934//===----------------------------------------------------------------------===//
4935// Helper functions used by the generated instruction selector.
4936//===----------------------------------------------------------------------===//
4937// Calls to these methods are generated by tblgen.
4938
4939/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4940/// the dag combiner simplified the 255, we still want to match. RHS is the
4941/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4942/// specified in the .td file (e.g. 255).
4943bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4944 int64_t DesiredMaskS) {
4945 uint64_t ActualMask = RHS->getValue();
4946 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4947
4948 // If the actual mask exactly matches, success!
4949 if (ActualMask == DesiredMask)
4950 return true;
4951
4952 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4953 if (ActualMask & ~DesiredMask)
4954 return false;
4955
4956 // Otherwise, the DAG Combiner may have proven that the value coming in is
4957 // either already zero or is not demanded. Check for known zero input bits.
4958 uint64_t NeededMask = DesiredMask & ~ActualMask;
4959 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4960 return true;
4961
4962 // TODO: check to see if missing bits are just not demanded.
4963
4964 // Otherwise, this pattern doesn't match.
4965 return false;
4966}
4967
4968/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4969/// the dag combiner simplified the 255, we still want to match. RHS is the
4970/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4971/// specified in the .td file (e.g. 255).
4972bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4973 int64_t DesiredMaskS) {
4974 uint64_t ActualMask = RHS->getValue();
4975 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4976
4977 // If the actual mask exactly matches, success!
4978 if (ActualMask == DesiredMask)
4979 return true;
4980
4981 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4982 if (ActualMask & ~DesiredMask)
4983 return false;
4984
4985 // Otherwise, the DAG Combiner may have proven that the value coming in is
4986 // either already zero or is not demanded. Check for known zero input bits.
4987 uint64_t NeededMask = DesiredMask & ~ActualMask;
4988
4989 uint64_t KnownZero, KnownOne;
4990 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4991
4992 // If all the missing bits in the or are already known to be set, match!
4993 if ((NeededMask & KnownOne) == NeededMask)
4994 return true;
4995
4996 // TODO: check to see if missing bits are just not demanded.
4997
4998 // Otherwise, this pattern doesn't match.
4999 return false;
5000}
5001
Jim Laskey03593f72006-08-01 18:29:48 +00005002
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005003/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5004/// by tblgen. Others should not call it.
5005void SelectionDAGISel::
5006SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5007 std::vector<SDOperand> InOps;
5008 std::swap(InOps, Ops);
5009
5010 Ops.push_back(InOps[0]); // input chain.
5011 Ops.push_back(InOps[1]); // input asm string.
5012
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005013 unsigned i = 2, e = InOps.size();
5014 if (InOps[e-1].getValueType() == MVT::Flag)
5015 --e; // Don't process a flag operand if it is here.
5016
5017 while (i != e) {
5018 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5019 if ((Flags & 7) != 4 /*MEM*/) {
5020 // Just skip over this operand, copying the operands verbatim.
5021 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5022 i += (Flags >> 3) + 1;
5023 } else {
5024 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5025 // Otherwise, this is a memory operand. Ask the target to select it.
5026 std::vector<SDOperand> SelOps;
5027 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00005028 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005029 exit(1);
5030 }
5031
5032 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00005033 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00005034 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00005035 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005036 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5037 i += 2;
5038 }
5039 }
5040
5041 // Add the flag input back if present.
5042 if (e != InOps.size())
5043 Ops.push_back(InOps.back());
5044}
Devang Patel09f162c2007-05-01 21:15:47 +00005045
Devang Patel8c78a0b2007-05-03 01:11:54 +00005046char SelectionDAGISel::ID = 0;