blob: 8c57c5806364c8cdace71a9fa3ca0ebcf858b242 [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.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"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Jim Laskey29e635d2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000187
188 /// isExportedInst - Return true if the specified value is an instruction
189 /// exported from its block.
190 bool isExportedInst(const Value *V) {
191 return ValueMap.count(V);
192 }
Misha Brukman835702a2005-04-21 22:36:52 +0000193
Chris Lattner49409cb2006-03-16 19:51:18 +0000194 unsigned CreateRegForValue(const Value *V);
195
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000205/// PHI nodes or outside of the basic block that defines it, or used by a
206/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000207static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
208 if (isa<PHINode>(I)) return true;
209 BasicBlock *BB = I->getParent();
210 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000211 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000212 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000213 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000214 return true;
215 return false;
216}
217
Chris Lattner6871b232005-10-30 19:42:35 +0000218/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000219/// entry block, return true. This includes arguments used by switches, since
220/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000221static bool isOnlyUsedInEntryBlock(Argument *A) {
222 BasicBlock *Entry = A->getParent()->begin();
223 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000224 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000225 return false; // Use not in entry block.
226 return true;
227}
228
Chris Lattner7a60d912005-01-07 07:47:53 +0000229FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000230 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000231 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
232
Chris Lattner6871b232005-10-30 19:42:35 +0000233 // Create a vreg for each argument register that is not dead and is used
234 // outside of the entry block for the function.
235 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
236 AI != E; ++AI)
237 if (!isOnlyUsedInEntryBlock(AI))
238 InitializeRegForValue(AI);
239
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 // Initialize the mapping of values to registers. This is only set up for
241 // instruction values that are used outside of the block that defines
242 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000243 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000246 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000247 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000248 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000249 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000250 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000251 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000252
Reid Spencere0fc4df2006-10-20 07:07:24 +0000253 // If the alignment of the value is smaller than the size of the
254 // value, and if the size of the value is particularly small
255 // (<= 8 bytes), round up to the size of the value for potentially
256 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000257 //
258 // FIXME: This could be made better with a preferred alignment hook in
259 // TargetData. It serves primarily to 8-byte align doubles for X86.
260 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000261 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000262 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000263 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000264 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000265 }
266
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000267 for (; BB != EB; ++BB)
268 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000269 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
270 if (!isa<AllocaInst>(I) ||
271 !StaticAllocaMap.count(cast<AllocaInst>(I)))
272 InitializeRegForValue(I);
273
274 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
275 // also creates the initial PHI MachineInstrs, though none of the input
276 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000277 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000278 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
279 MBBMap[BB] = MBB;
280 MF.getBasicBlockList().push_back(MBB);
281
282 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
283 // appropriate.
284 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000285 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
286 if (PN->use_empty()) continue;
287
288 MVT::ValueType VT = TLI.getValueType(PN->getType());
289 unsigned NumElements;
290 if (VT != MVT::Vector)
291 NumElements = TLI.getNumElements(VT);
292 else {
293 MVT::ValueType VT1,VT2;
294 NumElements =
295 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
296 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000297 }
Chris Lattner84a03502006-10-27 23:50:33 +0000298 unsigned PHIReg = ValueMap[PN];
299 assert(PHIReg && "PHI node does not have an assigned virtual register!");
300 for (unsigned i = 0; i != NumElements; ++i)
301 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
302 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000303 }
304}
305
Chris Lattner49409cb2006-03-16 19:51:18 +0000306/// CreateRegForValue - Allocate the appropriate number of virtual registers of
307/// the correctly promoted or expanded types. Assign these registers
308/// consecutive vreg numbers and return the first assigned number.
309unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
310 MVT::ValueType VT = TLI.getValueType(V->getType());
311
312 // The number of multiples of registers that we need, to, e.g., split up
313 // a <2 x int64> -> 4 x i32 registers.
314 unsigned NumVectorRegs = 1;
315
316 // If this is a packed type, figure out what type it will decompose into
317 // and how many of the elements it will use.
318 if (VT == MVT::Vector) {
319 const PackedType *PTy = cast<PackedType>(V->getType());
320 unsigned NumElts = PTy->getNumElements();
321 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
322
323 // Divide the input until we get to a supported size. This will always
324 // end with a scalar if the target doesn't support vectors.
325 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
326 NumElts >>= 1;
327 NumVectorRegs <<= 1;
328 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000329 if (NumElts == 1)
330 VT = EltTy;
331 else
332 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000333 }
334
335 // The common case is that we will only create one register for this
336 // value. If we have that case, create and return the virtual register.
337 unsigned NV = TLI.getNumElements(VT);
338 if (NV == 1) {
339 // If we are promoting this value, pick the next largest supported type.
340 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
341 unsigned Reg = MakeReg(PromotedType);
342 // If this is a vector of supported or promoted types (e.g. 4 x i16),
343 // create all of the registers.
344 for (unsigned i = 1; i != NumVectorRegs; ++i)
345 MakeReg(PromotedType);
346 return Reg;
347 }
348
349 // If this value is represented with multiple target registers, make sure
350 // to create enough consecutive registers of the right (smaller) type.
351 unsigned NT = VT-1; // Find the type to use.
352 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
353 --NT;
354
355 unsigned R = MakeReg((MVT::ValueType)NT);
356 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
357 MakeReg((MVT::ValueType)NT);
358 return R;
359}
Chris Lattner7a60d912005-01-07 07:47:53 +0000360
361//===----------------------------------------------------------------------===//
362/// SelectionDAGLowering - This is the common target-independent lowering
363/// implementation that is parameterized by a TargetLowering object.
364/// Also, targets can overload any lowering method.
365///
366namespace llvm {
367class SelectionDAGLowering {
368 MachineBasicBlock *CurMBB;
369
370 std::map<const Value*, SDOperand> NodeMap;
371
Chris Lattner4d9651c2005-01-17 22:19:26 +0000372 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
373 /// them up and then emit token factor nodes when possible. This allows us to
374 /// get simple disambiguation between loads without worrying about alias
375 /// analysis.
376 std::vector<SDOperand> PendingLoads;
377
Nate Begemaned728c12006-03-27 01:32:24 +0000378 /// Case - A pair of values to record the Value for a switch case, and the
379 /// case's target basic block.
380 typedef std::pair<Constant*, MachineBasicBlock*> Case;
381 typedef std::vector<Case>::iterator CaseItr;
382 typedef std::pair<CaseItr, CaseItr> CaseRange;
383
384 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
385 /// of conditional branches.
386 struct CaseRec {
387 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
388 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
389
390 /// CaseBB - The MBB in which to emit the compare and branch
391 MachineBasicBlock *CaseBB;
392 /// LT, GE - If nonzero, we know the current case value must be less-than or
393 /// greater-than-or-equal-to these Constants.
394 Constant *LT;
395 Constant *GE;
396 /// Range - A pair of iterators representing the range of case values to be
397 /// processed at this point in the binary search tree.
398 CaseRange Range;
399 };
400
401 /// The comparison function for sorting Case values.
402 struct CaseCmp {
403 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000404 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
405 if (I1->getType()->isUnsigned())
406 return I1->getZExtValue() <
407 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000408
Reid Spencere0fc4df2006-10-20 07:07:24 +0000409 return cast<const ConstantInt>(C1.first)->getSExtValue() <
410 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000411 }
412 };
413
Chris Lattner7a60d912005-01-07 07:47:53 +0000414public:
415 // TLI - This is information that describes the available target features we
416 // need for lowering. This indicates when operations are unavailable,
417 // implemented with a libcall, etc.
418 TargetLowering &TLI;
419 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000420 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000421
Nate Begemaned728c12006-03-27 01:32:24 +0000422 /// SwitchCases - Vector of CaseBlock structures used to communicate
423 /// SwitchInst code generation information.
424 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000425 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000426
Chris Lattner7a60d912005-01-07 07:47:53 +0000427 /// FuncInfo - Information about the function as a whole.
428 ///
429 FunctionLoweringInfo &FuncInfo;
430
431 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000432 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000434 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000435 }
436
Chris Lattner4108bb02005-01-17 19:43:36 +0000437 /// getRoot - Return the current virtual root of the Selection DAG.
438 ///
439 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000440 if (PendingLoads.empty())
441 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000442
Chris Lattner4d9651c2005-01-17 22:19:26 +0000443 if (PendingLoads.size() == 1) {
444 SDOperand Root = PendingLoads[0];
445 DAG.setRoot(Root);
446 PendingLoads.clear();
447 return Root;
448 }
449
450 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000451 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
452 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000453 PendingLoads.clear();
454 DAG.setRoot(Root);
455 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000456 }
457
Chris Lattnered0110b2006-10-27 21:36:01 +0000458 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
459
Chris Lattner7a60d912005-01-07 07:47:53 +0000460 void visit(Instruction &I) { visit(I.getOpcode(), I); }
461
462 void visit(unsigned Opcode, User &I) {
463 switch (Opcode) {
464 default: assert(0 && "Unknown instruction type encountered!");
465 abort();
466 // Build the switch statement using the Instruction.def file.
467#define HANDLE_INST(NUM, OPCODE, CLASS) \
468 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
469#include "llvm/Instruction.def"
470 }
471 }
472
473 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474
Chris Lattner4024c002006-03-15 22:19:46 +0000475 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000476 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000477 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000478
479 SDOperand getIntPtrConstant(uint64_t Val) {
480 return DAG.getConstant(Val, TLI.getPointerTy());
481 }
482
Chris Lattner8471b152006-03-16 19:57:50 +0000483 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000484
485 const SDOperand &setValue(const Value *V, SDOperand NewN) {
486 SDOperand &N = NodeMap[V];
487 assert(N.Val == 0 && "Already set a value for this node!");
488 return N = NewN;
489 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000490
Chris Lattner6f87d182006-02-22 22:37:12 +0000491 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 MVT::ValueType VT,
493 bool OutReg, bool InReg,
494 std::set<unsigned> &OutputRegs,
495 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000496
Chris Lattnered0110b2006-10-27 21:36:01 +0000497 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
498 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000500 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000501 void ExportFromCurrentBlock(Value *V);
502
Chris Lattner7a60d912005-01-07 07:47:53 +0000503 // Terminator instructions.
504 void visitRet(ReturnInst &I);
505 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000506 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508
Nate Begemaned728c12006-03-27 01:32:24 +0000509 // Helper for visitSwitch
510 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000511 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000512
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000514 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
515 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
516
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000517 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
518 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000519 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000520 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000521 if (I.getType()->isFloatingPoint())
522 visitFPBinary(I, ISD::FADD, ISD::VADD);
523 else
524 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000525 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000526 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000527 void visitMul(User &I) {
528 if (I.getType()->isFloatingPoint())
529 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
530 else
531 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000532 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000533 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
534 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
535 void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV, ISD::VSDIV); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000536 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000537 const Type *Ty = I.getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000538 if (Ty->isFloatingPoint())
539 visitFPBinary(I, ISD::FREM, 0);
540 else
541 visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000542 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000543 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
544 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
545 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000546 void visitShl(User &I) { visitShift(I, ISD::SHL); }
547 void visitShr(User &I) {
548 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000549 }
550
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000551 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
552 ISD::CondCode FPOpc);
553 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
554 ISD::SETOEQ); }
555 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
556 ISD::SETUNE); }
557 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
558 ISD::SETOLE); }
559 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
560 ISD::SETOGE); }
561 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
562 ISD::SETOLT); }
563 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
564 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000565
Chris Lattner67271862006-03-29 00:11:43 +0000566 void visitExtractElement(User &I);
567 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000568 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000569
Chris Lattner7a60d912005-01-07 07:47:53 +0000570 void visitGetElementPtr(User &I);
571 void visitCast(User &I);
572 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000573
574 void visitMalloc(MallocInst &I);
575 void visitFree(FreeInst &I);
576 void visitAlloca(AllocaInst &I);
577 void visitLoad(LoadInst &I);
578 void visitStore(StoreInst &I);
579 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
580 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000581 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000582 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000583 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000584
Chris Lattner7a60d912005-01-07 07:47:53 +0000585 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000586 void visitVAArg(VAArgInst &I);
587 void visitVAEnd(CallInst &I);
588 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000589 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000590
Chris Lattner875def92005-01-11 05:56:49 +0000591 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000592
593 void visitUserOp1(Instruction &I) {
594 assert(0 && "UserOp1 should not exist at instruction selection time!");
595 abort();
596 }
597 void visitUserOp2(Instruction &I) {
598 assert(0 && "UserOp2 should not exist at instruction selection time!");
599 abort();
600 }
601};
602} // end namespace llvm
603
Chris Lattner8471b152006-03-16 19:57:50 +0000604SDOperand SelectionDAGLowering::getValue(const Value *V) {
605 SDOperand &N = NodeMap[V];
606 if (N.Val) return N;
607
608 const Type *VTy = V->getType();
609 MVT::ValueType VT = TLI.getValueType(VTy);
610 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
612 visit(CE->getOpcode(), *CE);
613 assert(N.Val && "visit didn't populate the ValueMap!");
614 return N;
615 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
616 return N = DAG.getGlobalAddress(GV, VT);
617 } else if (isa<ConstantPointerNull>(C)) {
618 return N = DAG.getConstant(0, TLI.getPointerTy());
619 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000620 if (!isa<PackedType>(VTy))
621 return N = DAG.getNode(ISD::UNDEF, VT);
622
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000623 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000624 const PackedType *PTy = cast<PackedType>(VTy);
625 unsigned NumElements = PTy->getNumElements();
626 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
627
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000628 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000629 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
630
631 // Create a VConstant node with generic Vector type.
632 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
633 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000634 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
635 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000636 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
637 return N = DAG.getConstantFP(CFP->getValue(), VT);
638 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
639 unsigned NumElements = PTy->getNumElements();
640 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000641
642 // Now that we know the number and type of the elements, push a
643 // Constant or ConstantFP node onto the ops list for each element of
644 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000645 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000646 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000647 for (unsigned i = 0; i != NumElements; ++i)
648 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000649 } else {
650 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
651 SDOperand Op;
652 if (MVT::isFloatingPoint(PVT))
653 Op = DAG.getConstantFP(0, PVT);
654 else
655 Op = DAG.getConstant(0, PVT);
656 Ops.assign(NumElements, Op);
657 }
658
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000659 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000660 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
661 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000662 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000663 } else {
664 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000665 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000666 }
667 }
668
669 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
670 std::map<const AllocaInst*, int>::iterator SI =
671 FuncInfo.StaticAllocaMap.find(AI);
672 if (SI != FuncInfo.StaticAllocaMap.end())
673 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
674 }
675
676 std::map<const Value*, unsigned>::const_iterator VMI =
677 FuncInfo.ValueMap.find(V);
678 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
679
680 unsigned InReg = VMI->second;
681
682 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000683 if (VT != MVT::Vector) {
684 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000685
Chris Lattner5fe1f542006-03-31 02:06:56 +0000686 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
687 if (DestVT < VT) {
688 // Source must be expanded. This input value is actually coming from the
689 // register pair VMI->second and VMI->second+1.
690 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
691 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
692 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000693 if (MVT::isFloatingPoint(VT))
694 N = DAG.getNode(ISD::FP_ROUND, VT, N);
695 else
696 N = DAG.getNode(ISD::TRUNCATE, VT, N);
697 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000698 } else {
699 // Otherwise, if this is a vector, make it available as a generic vector
700 // here.
701 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000702 const PackedType *PTy = cast<PackedType>(VTy);
703 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000704 PTyLegalElementVT);
705
706 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000707 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000708 if (PTyElementVT == PTyLegalElementVT) {
709 // If the value types are legal, just VBUILD the CopyFromReg nodes.
710 for (unsigned i = 0; i != NE; ++i)
711 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
712 PTyElementVT));
713 } else if (PTyElementVT < PTyLegalElementVT) {
714 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
715 for (unsigned i = 0; i != NE; ++i) {
716 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
717 PTyElementVT);
718 if (MVT::isFloatingPoint(PTyElementVT))
719 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
720 else
721 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
722 Ops.push_back(Op);
723 }
724 } else {
725 // If the register was expanded, use BUILD_PAIR.
726 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
727 for (unsigned i = 0; i != NE/2; ++i) {
728 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
729 PTyElementVT);
730 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
731 PTyElementVT);
732 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
733 }
734 }
735
736 Ops.push_back(DAG.getConstant(NE, MVT::i32));
737 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000738 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000739
740 // Finally, use a VBIT_CONVERT to make this available as the appropriate
741 // vector type.
742 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
743 DAG.getConstant(PTy->getNumElements(),
744 MVT::i32),
745 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000746 }
747
748 return N;
749}
750
751
Chris Lattner7a60d912005-01-07 07:47:53 +0000752void SelectionDAGLowering::visitRet(ReturnInst &I) {
753 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000754 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000755 return;
756 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000757 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000758 NewValues.push_back(getRoot());
759 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
760 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000761 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000762
763 // If this is an integer return value, we need to promote it ourselves to
764 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
765 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000766 // FIXME: C calling convention requires the return type to be promoted to
767 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000768 if (MVT::isInteger(RetOp.getValueType()) &&
769 RetOp.getValueType() < MVT::i64) {
770 MVT::ValueType TmpVT;
771 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
772 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
773 else
774 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000775
Evan Chenga2e99532006-05-26 23:09:09 +0000776 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000777 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
778 else
779 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
780 }
781 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000782 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000783 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000784 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
785 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000786}
787
Chris Lattnered0110b2006-10-27 21:36:01 +0000788/// ExportFromCurrentBlock - If this condition isn't known to be exported from
789/// the current basic block, add it to ValueMap now so that we'll get a
790/// CopyTo/FromReg.
791void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
792 // No need to export constants.
793 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
794
795 // Already exported?
796 if (FuncInfo.isExportedInst(V)) return;
797
798 unsigned Reg = FuncInfo.InitializeRegForValue(V);
799 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
800}
801
Chris Lattner84a03502006-10-27 23:50:33 +0000802bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
803 const BasicBlock *FromBB) {
804 // The operands of the setcc have to be in this block. We don't know
805 // how to export them from some other block.
806 if (Instruction *VI = dyn_cast<Instruction>(V)) {
807 // Can export from current BB.
808 if (VI->getParent() == FromBB)
809 return true;
810
811 // Is already exported, noop.
812 return FuncInfo.isExportedInst(V);
813 }
814
815 // If this is an argument, we can export it if the BB is the entry block or
816 // if it is already exported.
817 if (isa<Argument>(V)) {
818 if (FromBB == &FromBB->getParent()->getEntryBlock())
819 return true;
820
821 // Otherwise, can only export this if it is already exported.
822 return FuncInfo.isExportedInst(V);
823 }
824
825 // Otherwise, constants can always be exported.
826 return true;
827}
828
Chris Lattnered0110b2006-10-27 21:36:01 +0000829/// FindMergedConditions - If Cond is an expression like
830void SelectionDAGLowering::FindMergedConditions(Value *Cond,
831 MachineBasicBlock *TBB,
832 MachineBasicBlock *FBB,
833 MachineBasicBlock *CurBB,
834 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000835 // If this node is not part of the or/and tree, emit it as a branch.
836 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
837
838 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
839 BOp->getParent() != CurBB->getBasicBlock()) {
840 const BasicBlock *BB = CurBB->getBasicBlock();
841
842 // If the leaf of the tree is a setcond inst, merge the condition into the
843 // caseblock.
844 if (BOp && isa<SetCondInst>(BOp) &&
845 // The operands of the setcc have to be in this block. We don't know
846 // how to export them from some other block.
Chris Lattner84a03502006-10-27 23:50:33 +0000847 isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
848 isExportableFromCurrentBlock(BOp->getOperand(1), BB)) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000849 ExportFromCurrentBlock(BOp->getOperand(0));
850 ExportFromCurrentBlock(BOp->getOperand(1));
851
852 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
853 switch (BOp->getOpcode()) {
854 default: assert(0 && "Unknown setcc opcode!");
855 case Instruction::SetEQ:
856 SignCond = ISD::SETEQ;
857 UnsCond = ISD::SETEQ;
858 FPCond = ISD::SETOEQ;
859 break;
860 case Instruction::SetNE:
861 SignCond = ISD::SETNE;
862 UnsCond = ISD::SETNE;
863 FPCond = ISD::SETUNE;
864 break;
865 case Instruction::SetLE:
866 SignCond = ISD::SETLE;
867 UnsCond = ISD::SETULE;
868 FPCond = ISD::SETOLE;
869 break;
870 case Instruction::SetGE:
871 SignCond = ISD::SETGE;
872 UnsCond = ISD::SETUGE;
873 FPCond = ISD::SETOGE;
874 break;
875 case Instruction::SetLT:
876 SignCond = ISD::SETLT;
877 UnsCond = ISD::SETULT;
878 FPCond = ISD::SETOLT;
879 break;
880 case Instruction::SetGT:
881 SignCond = ISD::SETGT;
882 UnsCond = ISD::SETUGT;
883 FPCond = ISD::SETOGT;
884 break;
885 }
886
887 const Type *OpType = BOp->getOperand(0)->getType();
888 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
889 OpType = PTy->getElementType();
890
891 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
892 Condition = FPCond;
893 else if (OpType->isUnsigned())
894 Condition = UnsCond;
895 else
896 Condition = SignCond;
897
898 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
899 BOp->getOperand(1), TBB, FBB, CurBB);
900 SwitchCases.push_back(CB);
901 return;
902 }
903
904 // Create a CaseBlock record representing this branch.
905 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
906 TBB, FBB, CurBB);
907 SwitchCases.push_back(CB);
908 ExportFromCurrentBlock(Cond);
909 return;
910 }
911
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000912
913 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000914 MachineFunction::iterator BBI = CurBB;
915 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
916 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
917
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000918 if (Opc == Instruction::Or) {
919 // Codegen X | Y as:
920 // jmp_if_X TBB
921 // jmp TmpBB
922 // TmpBB:
923 // jmp_if_Y TBB
924 // jmp FBB
925 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000926
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000927 // Emit the LHS condition.
928 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
929
930 // Emit the RHS condition into TmpBB.
931 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
932 } else {
933 assert(Opc == Instruction::And && "Unknown merge op!");
934 // Codegen X & Y as:
935 // jmp_if_X TmpBB
936 // jmp FBB
937 // TmpBB:
938 // jmp_if_Y TBB
939 // jmp FBB
940 //
941 // This requires creation of TmpBB after CurBB.
942
943 // Emit the LHS condition.
944 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
945
946 // Emit the RHS condition into TmpBB.
947 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
948 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000949}
950
Chris Lattner7a60d912005-01-07 07:47:53 +0000951void SelectionDAGLowering::visitBr(BranchInst &I) {
952 // Update machine-CFG edges.
953 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000954
955 // Figure out which block is immediately after the current one.
956 MachineBasicBlock *NextBlock = 0;
957 MachineFunction::iterator BBI = CurMBB;
958 if (++BBI != CurMBB->getParent()->end())
959 NextBlock = BBI;
960
961 if (I.isUnconditional()) {
962 // If this is not a fall-through branch, emit the branch.
963 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000964 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000965 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000966
Chris Lattner963ddad2006-10-24 17:57:59 +0000967 // Update machine-CFG edges.
968 CurMBB->addSuccessor(Succ0MBB);
969
970 return;
971 }
972
973 // If this condition is one of the special cases we handle, do special stuff
974 // now.
975 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000976 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000977
978 // If this is a series of conditions that are or'd or and'd together, emit
979 // this as a sequence of branches instead of setcc's with and/or operations.
980 // For example, instead of something like:
981 // cmp A, B
982 // C = seteq
983 // cmp D, E
984 // F = setle
985 // or C, F
986 // jnz foo
987 // Emit:
988 // cmp A, B
989 // je foo
990 // cmp D, E
991 // jle foo
992 //
993 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
994 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000995 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000996 BOp->getOpcode() == Instruction::Or)) {
997 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnered0110b2006-10-27 21:36:01 +0000998 visitSwitchCase(SwitchCases[0]);
999 SwitchCases.erase(SwitchCases.begin());
1000 return;
1001 }
1002 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001003
1004 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +00001005 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001006 Succ0MBB, Succ1MBB, CurMBB);
1007 // Use visitSwitchCase to actually insert the fast branch sequence for this
1008 // cond branch.
1009 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001010}
1011
Nate Begemaned728c12006-03-27 01:32:24 +00001012/// visitSwitchCase - Emits the necessary code to represent a single node in
1013/// the binary search tree resulting from lowering a switch instruction.
1014void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001015 SDOperand Cond;
1016 SDOperand CondLHS = getValue(CB.CmpLHS);
1017
Chris Lattnered0110b2006-10-27 21:36:01 +00001018 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1019 // handle common cases produced by branch lowering.
1020 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001021 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001022 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1023 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1024 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1025 } else
1026 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001027
1028 // Set NextBlock to be the MBB immediately after the current one, if any.
1029 // This is used to avoid emitting unnecessary branches to the next block.
1030 MachineBasicBlock *NextBlock = 0;
1031 MachineFunction::iterator BBI = CurMBB;
1032 if (++BBI != CurMBB->getParent()->end())
1033 NextBlock = BBI;
1034
1035 // If the lhs block is the next block, invert the condition so that we can
1036 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001037 if (CB.TrueBB == NextBlock) {
1038 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001039 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1040 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1041 }
1042 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001043 DAG.getBasicBlock(CB.TrueBB));
1044 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001045 DAG.setRoot(BrCond);
1046 else
1047 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001048 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001049 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001050 CurMBB->addSuccessor(CB.TrueBB);
1051 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001052}
1053
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001054void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001055 // Emit the code for the jump table
1056 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001057 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
1058 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +00001059 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001060 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +00001061 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001062 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1063 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001064 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +00001065 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
1066 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +00001067 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001068 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +00001069 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +00001070 // For Pic, the sequence is:
1071 // BRIND(load(Jumptable + index) + RelocBase)
1072 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +00001073 SDOperand Reloc;
1074 if (TLI.usesGlobalOffsetTable())
1075 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1076 else
1077 Reloc = TAB;
Chris Lattner4c3ef472006-10-22 22:47:10 +00001078 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1079 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman78756502006-07-27 01:13:04 +00001080 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
1081 } else {
1082 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
1083 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001084}
1085
Nate Begemaned728c12006-03-27 01:32:24 +00001086void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1087 // Figure out which block is immediately after the current one.
1088 MachineBasicBlock *NextBlock = 0;
1089 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001090
Nate Begemaned728c12006-03-27 01:32:24 +00001091 if (++BBI != CurMBB->getParent()->end())
1092 NextBlock = BBI;
1093
Chris Lattner6d6fc262006-10-22 21:36:53 +00001094 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1095
Nate Begemaned728c12006-03-27 01:32:24 +00001096 // If there is only the default destination, branch to it if it is not the
1097 // next basic block. Otherwise, just fall through.
1098 if (I.getNumOperands() == 2) {
1099 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001100
Nate Begemaned728c12006-03-27 01:32:24 +00001101 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001102 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001103 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001104 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001105
Chris Lattner6d6fc262006-10-22 21:36:53 +00001106 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001107 return;
1108 }
1109
1110 // If there are any non-default case statements, create a vector of Cases
1111 // representing each one, and sort the vector so that we can efficiently
1112 // create a binary search tree from them.
1113 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001114
Nate Begemaned728c12006-03-27 01:32:24 +00001115 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1116 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1117 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1118 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001119
Nate Begemaned728c12006-03-27 01:32:24 +00001120 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1121
1122 // Get the Value to be switched on and default basic blocks, which will be
1123 // inserted into CaseBlock records, representing basic blocks in the binary
1124 // search tree.
1125 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001126
1127 // Get the MachineFunction which holds the current MBB. This is used during
1128 // emission of jump tables, and when inserting any additional MBBs necessary
1129 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001130 MachineFunction *CurMF = CurMBB->getParent();
1131 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001132
1133 // If the switch has few cases (two or less) emit a series of specific
1134 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001135 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001136 // TODO: If any two of the cases has the same destination, and if one value
1137 // is the same as the other, but has one bit unset that the other has set,
1138 // use bit manipulation to do two compares at once. For example:
1139 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1140
Chris Lattner4c931502006-10-23 18:38:22 +00001141 // Rearrange the case blocks so that the last one falls through if possible.
1142 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1143 // The last case block won't fall through into 'NextBlock' if we emit the
1144 // branches in this order. See if rearranging a case value would help.
1145 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1146 if (Cases[i].second == NextBlock) {
1147 std::swap(Cases[i], Cases.back());
1148 break;
1149 }
1150 }
1151 }
1152
Chris Lattner6d6fc262006-10-22 21:36:53 +00001153 // Create a CaseBlock record representing a conditional branch to
1154 // the Case's target mbb if the value being switched on SV is equal
1155 // to C.
1156 MachineBasicBlock *CurBlock = CurMBB;
1157 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1158 MachineBasicBlock *FallThrough;
1159 if (i != e-1) {
1160 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1161 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1162 } else {
1163 // If the last case doesn't match, go to the default block.
1164 FallThrough = Default;
1165 }
1166
1167 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1168 Cases[i].second, FallThrough, CurBlock);
1169
1170 // If emitting the first comparison, just call visitSwitchCase to emit the
1171 // code into the current block. Otherwise, push the CaseBlock onto the
1172 // vector to be later processed by SDISel, and insert the node's MBB
1173 // before the next MBB.
1174 if (CurBlock == CurMBB)
1175 visitSwitchCase(CB);
1176 else
1177 SwitchCases.push_back(CB);
1178
1179 CurBlock = FallThrough;
1180 }
1181 return;
1182 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001183
Nate Begemand7a19102006-05-08 16:51:36 +00001184 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1185 // target supports indirect branches, then emit a jump table rather than
1186 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +00001187 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +00001188 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001189 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1190 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001191 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1192
Nate Begemand7a19102006-05-08 16:51:36 +00001193 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001194 // Create a new basic block to hold the code for loading the address
1195 // of the jump table, and jumping to it. Update successor information;
1196 // we will either branch to the default case for the switch, or the jump
1197 // table.
1198 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1199 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1200 CurMBB->addSuccessor(Default);
1201 CurMBB->addSuccessor(JumpTableBB);
1202
1203 // Subtract the lowest switch case value from the value being switched on
1204 // and conditional branch to default mbb if the result is greater than the
1205 // difference between smallest and largest cases.
1206 SDOperand SwitchOp = getValue(SV);
1207 MVT::ValueType VT = SwitchOp.getValueType();
1208 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1209 DAG.getConstant(First, VT));
1210
1211 // The SDNode we just created, which holds the value being switched on
1212 // minus the the smallest case value, needs to be copied to a virtual
1213 // register so it can be used as an index into the jump table in a
1214 // subsequent basic block. This value may be smaller or larger than the
1215 // target's pointer type, and therefore require extension or truncating.
1216 if (VT > TLI.getPointerTy())
1217 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1218 else
1219 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001220
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001221 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1222 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1223
1224 // Emit the range check for the jump table, and branch to the default
1225 // block for the switch statement if the value being switched on exceeds
1226 // the largest case in the switch.
1227 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1228 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1229 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1230 DAG.getBasicBlock(Default)));
1231
Nate Begemandf488392006-05-03 03:48:02 +00001232 // Build a vector of destination BBs, corresponding to each target
1233 // of the jump table. If the value of the jump table slot corresponds to
1234 // a case statement, push the case's BB onto the vector, otherwise, push
1235 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001236 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001237 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001238 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001239 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001240 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001241 ++ii;
1242 } else {
1243 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001244 }
Nate Begemandf488392006-05-03 03:48:02 +00001245
Chris Lattner84a03502006-10-27 23:50:33 +00001246 // Update successor info. Add one edge to each unique successor.
1247 // Vector bool would be better, but vector<bool> is really slow.
1248 std::vector<unsigned char> SuccsHandled;
1249 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1250
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001251 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001252 E = DestBBs.end(); I != E; ++I) {
1253 if (!SuccsHandled[(*I)->getNumber()]) {
1254 SuccsHandled[(*I)->getNumber()] = true;
1255 JumpTableBB->addSuccessor(*I);
1256 }
1257 }
Nate Begemandf488392006-05-03 03:48:02 +00001258
1259 // Create a jump table index for this jump table, or return an existing
1260 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001261 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1262
1263 // Set the jump table information so that we can codegen it as a second
1264 // MachineBasicBlock
1265 JT.Reg = JumpTableReg;
1266 JT.JTI = JTI;
1267 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001268 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001269 return;
1270 }
1271 }
Nate Begemaned728c12006-03-27 01:32:24 +00001272
1273 // Push the initial CaseRec onto the worklist
1274 std::vector<CaseRec> CaseVec;
1275 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1276
1277 while (!CaseVec.empty()) {
1278 // Grab a record representing a case range to process off the worklist
1279 CaseRec CR = CaseVec.back();
1280 CaseVec.pop_back();
1281
1282 // Size is the number of Cases represented by this range. If Size is 1,
1283 // then we are processing a leaf of the binary search tree. Otherwise,
1284 // we need to pick a pivot, and push left and right ranges onto the
1285 // worklist.
1286 unsigned Size = CR.Range.second - CR.Range.first;
1287
1288 if (Size == 1) {
1289 // Create a CaseBlock record representing a conditional branch to
1290 // the Case's target mbb if the value being switched on SV is equal
1291 // to C. Otherwise, branch to default.
1292 Constant *C = CR.Range.first->first;
1293 MachineBasicBlock *Target = CR.Range.first->second;
1294 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1295 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001296
Nate Begemaned728c12006-03-27 01:32:24 +00001297 // If the MBB representing the leaf node is the current MBB, then just
1298 // call visitSwitchCase to emit the code into the current block.
1299 // Otherwise, push the CaseBlock onto the vector to be later processed
1300 // by SDISel, and insert the node's MBB before the next MBB.
1301 if (CR.CaseBB == CurMBB)
1302 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001303 else
Nate Begemaned728c12006-03-27 01:32:24 +00001304 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001305 } else {
1306 // split case range at pivot
1307 CaseItr Pivot = CR.Range.first + (Size / 2);
1308 CaseRange LHSR(CR.Range.first, Pivot);
1309 CaseRange RHSR(Pivot, CR.Range.second);
1310 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001311 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001312
Nate Begemaned728c12006-03-27 01:32:24 +00001313 // We know that we branch to the LHS if the Value being switched on is
1314 // less than the Pivot value, C. We use this to optimize our binary
1315 // tree a bit, by recognizing that if SV is greater than or equal to the
1316 // LHS's Case Value, and that Case Value is exactly one less than the
1317 // Pivot's Value, then we can branch directly to the LHS's Target,
1318 // rather than creating a leaf node for it.
1319 if ((LHSR.second - LHSR.first) == 1 &&
1320 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001321 cast<ConstantIntegral>(C)->getZExtValue() ==
1322 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001323 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001324 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001325 TrueBB = new MachineBasicBlock(LLVMBB);
1326 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1327 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001328 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001329
Nate Begemaned728c12006-03-27 01:32:24 +00001330 // Similar to the optimization above, if the Value being switched on is
1331 // known to be less than the Constant CR.LT, and the current Case Value
1332 // is CR.LT - 1, then we can branch directly to the target block for
1333 // the current Case Value, rather than emitting a RHS leaf node for it.
1334 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001335 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1336 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001337 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001338 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001339 FalseBB = new MachineBasicBlock(LLVMBB);
1340 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1341 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001342 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001343
Nate Begemaned728c12006-03-27 01:32:24 +00001344 // Create a CaseBlock record representing a conditional branch to
1345 // the LHS node if the value being switched on SV is less than C.
1346 // Otherwise, branch to LHS.
1347 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001348 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001349
Nate Begemaned728c12006-03-27 01:32:24 +00001350 if (CR.CaseBB == CurMBB)
1351 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001352 else
Nate Begemaned728c12006-03-27 01:32:24 +00001353 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001354 }
1355 }
1356}
1357
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001358void SelectionDAGLowering::visitSub(User &I) {
1359 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001360 if (I.getType()->isFloatingPoint()) {
1361 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1362 if (CFP->isExactlyValue(-0.0)) {
1363 SDOperand Op2 = getValue(I.getOperand(1));
1364 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1365 return;
1366 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001367 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1368 } else
1369 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001370}
1371
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001372void
1373SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001374 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001375 SDOperand Op1 = getValue(I.getOperand(0));
1376 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001377
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001378 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001379 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1380 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1381 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001382 } else {
1383 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1384 }
1385}
1386
1387void
1388SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1389 const Type *Ty = I.getType();
1390 SDOperand Op1 = getValue(I.getOperand(0));
1391 SDOperand Op2 = getValue(I.getOperand(1));
1392
1393 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1394 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1395 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1396 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1397 } else {
1398 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001399 }
Nate Begeman127321b2005-11-18 07:42:56 +00001400}
Chris Lattner96c26752005-01-19 22:31:21 +00001401
Nate Begeman127321b2005-11-18 07:42:56 +00001402void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1403 SDOperand Op1 = getValue(I.getOperand(0));
1404 SDOperand Op2 = getValue(I.getOperand(1));
1405
1406 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1407
Chris Lattner7a60d912005-01-07 07:47:53 +00001408 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1409}
1410
1411void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001412 ISD::CondCode UnsignedOpcode,
1413 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001414 SDOperand Op1 = getValue(I.getOperand(0));
1415 SDOperand Op2 = getValue(I.getOperand(1));
1416 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001417 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001418 Opcode = FPOpcode;
1419 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001420 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001421 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001422}
1423
1424void SelectionDAGLowering::visitSelect(User &I) {
1425 SDOperand Cond = getValue(I.getOperand(0));
1426 SDOperand TrueVal = getValue(I.getOperand(1));
1427 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001428 if (!isa<PackedType>(I.getType())) {
1429 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1430 TrueVal, FalseVal));
1431 } else {
1432 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1433 *(TrueVal.Val->op_end()-2),
1434 *(TrueVal.Val->op_end()-1)));
1435 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001436}
1437
1438void SelectionDAGLowering::visitCast(User &I) {
1439 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001440 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001441 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001442
Chris Lattner2f4119a2006-03-22 20:09:35 +00001443 if (DestVT == MVT::Vector) {
1444 // This is a cast to a vector from something else. This is always a bit
1445 // convert. Get information about the input vector.
1446 const PackedType *DestTy = cast<PackedType>(I.getType());
1447 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1448 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1449 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1450 DAG.getValueType(EltVT)));
1451 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001452 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001453 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001454 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001455 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001456 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001457 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001458 } else if (isInteger(SrcVT)) {
1459 if (isInteger(DestVT)) { // Int -> Int cast
1460 if (DestVT < SrcVT) // Truncating cast?
1461 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001462 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001463 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001464 else
Chris Lattner4024c002006-03-15 22:19:46 +00001465 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001466 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001467 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001468 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001469 else
Chris Lattner4024c002006-03-15 22:19:46 +00001470 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001471 } else {
1472 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001473 }
Chris Lattner4024c002006-03-15 22:19:46 +00001474 } else if (isFloatingPoint(SrcVT)) {
1475 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1476 if (DestVT < SrcVT) // Rounding cast?
1477 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001478 else
Chris Lattner4024c002006-03-15 22:19:46 +00001479 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001480 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001481 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001482 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001483 else
Chris Lattner4024c002006-03-15 22:19:46 +00001484 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001485 } else {
1486 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001487 }
1488 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001489 assert(SrcVT == MVT::Vector && "Unknown cast!");
1490 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1491 // This is a cast from a vector to something else. This is always a bit
1492 // convert. Get information about the input vector.
1493 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001494 }
1495}
1496
Chris Lattner67271862006-03-29 00:11:43 +00001497void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001498 SDOperand InVec = getValue(I.getOperand(0));
1499 SDOperand InVal = getValue(I.getOperand(1));
1500 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1501 getValue(I.getOperand(2)));
1502
Chris Lattner29b23012006-03-19 01:17:20 +00001503 SDOperand Num = *(InVec.Val->op_end()-2);
1504 SDOperand Typ = *(InVec.Val->op_end()-1);
1505 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1506 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001507}
1508
Chris Lattner67271862006-03-29 00:11:43 +00001509void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001510 SDOperand InVec = getValue(I.getOperand(0));
1511 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1512 getValue(I.getOperand(1)));
1513 SDOperand Typ = *(InVec.Val->op_end()-1);
1514 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1515 TLI.getValueType(I.getType()), InVec, InIdx));
1516}
Chris Lattner32206f52006-03-18 01:44:44 +00001517
Chris Lattner098c01e2006-04-08 04:15:24 +00001518void SelectionDAGLowering::visitShuffleVector(User &I) {
1519 SDOperand V1 = getValue(I.getOperand(0));
1520 SDOperand V2 = getValue(I.getOperand(1));
1521 SDOperand Mask = getValue(I.getOperand(2));
1522
1523 SDOperand Num = *(V1.Val->op_end()-2);
1524 SDOperand Typ = *(V2.Val->op_end()-1);
1525 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1526 V1, V2, Mask, Num, Typ));
1527}
1528
1529
Chris Lattner7a60d912005-01-07 07:47:53 +00001530void SelectionDAGLowering::visitGetElementPtr(User &I) {
1531 SDOperand N = getValue(I.getOperand(0));
1532 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001533
1534 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1535 OI != E; ++OI) {
1536 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001537 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001538 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001539 if (Field) {
1540 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001541 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001542 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001543 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001544 }
1545 Ty = StTy->getElementType(Field);
1546 } else {
1547 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001548
Chris Lattner43535a12005-11-09 04:45:33 +00001549 // If this is a constant subscript, handle it quickly.
1550 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001551 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001552 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001553 if (CI->getType()->isSigned())
1554 Offs = (int64_t)
1555 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001556 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001557 Offs =
1558 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001559 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1560 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001561 }
Chris Lattner43535a12005-11-09 04:45:33 +00001562
1563 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001564 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001565 SDOperand IdxN = getValue(Idx);
1566
1567 // If the index is smaller or larger than intptr_t, truncate or extend
1568 // it.
1569 if (IdxN.getValueType() < N.getValueType()) {
1570 if (Idx->getType()->isSigned())
1571 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1572 else
1573 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1574 } else if (IdxN.getValueType() > N.getValueType())
1575 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1576
1577 // If this is a multiply by a power of two, turn it into a shl
1578 // immediately. This is a very common case.
1579 if (isPowerOf2_64(ElementSize)) {
1580 unsigned Amt = Log2_64(ElementSize);
1581 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001582 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001583 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1584 continue;
1585 }
1586
1587 SDOperand Scale = getIntPtrConstant(ElementSize);
1588 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1589 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001590 }
1591 }
1592 setValue(&I, N);
1593}
1594
1595void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1596 // If this is a fixed sized alloca in the entry block of the function,
1597 // allocate it statically on the stack.
1598 if (FuncInfo.StaticAllocaMap.count(&I))
1599 return; // getValue will auto-populate this.
1600
1601 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001602 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1603 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001604 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001605
1606 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001607 MVT::ValueType IntPtr = TLI.getPointerTy();
1608 if (IntPtr < AllocSize.getValueType())
1609 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1610 else if (IntPtr > AllocSize.getValueType())
1611 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001612
Chris Lattnereccb73d2005-01-22 23:04:37 +00001613 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001614 getIntPtrConstant(TySize));
1615
1616 // Handle alignment. If the requested alignment is less than or equal to the
1617 // stack alignment, ignore it and round the size of the allocation up to the
1618 // stack alignment size. If the size is greater than the stack alignment, we
1619 // note this in the DYNAMIC_STACKALLOC node.
1620 unsigned StackAlign =
1621 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1622 if (Align <= StackAlign) {
1623 Align = 0;
1624 // Add SA-1 to the size.
1625 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1626 getIntPtrConstant(StackAlign-1));
1627 // Mask out the low bits for alignment purposes.
1628 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1629 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1630 }
1631
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001632 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001633 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1634 MVT::Other);
1635 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001636 DAG.setRoot(setValue(&I, DSA).getValue(1));
1637
1638 // Inform the Frame Information that we have just allocated a variable-sized
1639 // object.
1640 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1641}
1642
Chris Lattner7a60d912005-01-07 07:47:53 +00001643void SelectionDAGLowering::visitLoad(LoadInst &I) {
1644 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001645
Chris Lattner4d9651c2005-01-17 22:19:26 +00001646 SDOperand Root;
1647 if (I.isVolatile())
1648 Root = getRoot();
1649 else {
1650 // Do not serialize non-volatile loads against each other.
1651 Root = DAG.getRoot();
1652 }
Chris Lattner4024c002006-03-15 22:19:46 +00001653
Evan Chenge71fe34d2006-10-09 20:57:25 +00001654 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001655 Root, I.isVolatile()));
1656}
1657
1658SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001659 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001660 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001661 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001662 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001663 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001664 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1665 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001666 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001667 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001668 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001669
Chris Lattner4024c002006-03-15 22:19:46 +00001670 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001671 DAG.setRoot(L.getValue(1));
1672 else
1673 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001674
1675 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001676}
1677
1678
1679void SelectionDAGLowering::visitStore(StoreInst &I) {
1680 Value *SrcV = I.getOperand(0);
1681 SDOperand Src = getValue(SrcV);
1682 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001683 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1684 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001685}
1686
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001687/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1688/// access memory and has no other side effects at all.
1689static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1690#define GET_NO_MEMORY_INTRINSICS
1691#include "llvm/Intrinsics.gen"
1692#undef GET_NO_MEMORY_INTRINSICS
1693 return false;
1694}
1695
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001696// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1697// have any side-effects or if it only reads memory.
1698static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1699#define GET_SIDE_EFFECT_INFO
1700#include "llvm/Intrinsics.gen"
1701#undef GET_SIDE_EFFECT_INFO
1702 return false;
1703}
1704
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001705/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1706/// node.
1707void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1708 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001709 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001710 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001711
1712 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001713 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001714 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1715 if (OnlyLoad) {
1716 // We don't need to serialize loads against other loads.
1717 Ops.push_back(DAG.getRoot());
1718 } else {
1719 Ops.push_back(getRoot());
1720 }
1721 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001722
1723 // Add the intrinsic ID as an integer operand.
1724 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1725
1726 // Add all operands of the call to the operand list.
1727 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1728 SDOperand Op = getValue(I.getOperand(i));
1729
1730 // If this is a vector type, force it to the right packed type.
1731 if (Op.getValueType() == MVT::Vector) {
1732 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1733 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1734
1735 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1736 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1737 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1738 }
1739
1740 assert(TLI.isTypeLegal(Op.getValueType()) &&
1741 "Intrinsic uses a non-legal type?");
1742 Ops.push_back(Op);
1743 }
1744
1745 std::vector<MVT::ValueType> VTs;
1746 if (I.getType() != Type::VoidTy) {
1747 MVT::ValueType VT = TLI.getValueType(I.getType());
1748 if (VT == MVT::Vector) {
1749 const PackedType *DestTy = cast<PackedType>(I.getType());
1750 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1751
1752 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1753 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1754 }
1755
1756 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1757 VTs.push_back(VT);
1758 }
1759 if (HasChain)
1760 VTs.push_back(MVT::Other);
1761
Chris Lattnerbd887772006-08-14 23:53:35 +00001762 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1763
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001764 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001765 SDOperand Result;
1766 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001767 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1768 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001769 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001770 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1771 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001772 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001773 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1774 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001775
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001776 if (HasChain) {
1777 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1778 if (OnlyLoad)
1779 PendingLoads.push_back(Chain);
1780 else
1781 DAG.setRoot(Chain);
1782 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001783 if (I.getType() != Type::VoidTy) {
1784 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1785 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1786 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1787 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1788 DAG.getValueType(EVT));
1789 }
1790 setValue(&I, Result);
1791 }
1792}
1793
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001794/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1795/// we want to emit this as a call to a named external function, return the name
1796/// otherwise lower it and return null.
1797const char *
1798SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1799 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001800 default:
1801 // By default, turn this into a target intrinsic node.
1802 visitTargetIntrinsic(I, Intrinsic);
1803 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001804 case Intrinsic::vastart: visitVAStart(I); return 0;
1805 case Intrinsic::vaend: visitVAEnd(I); return 0;
1806 case Intrinsic::vacopy: visitVACopy(I); return 0;
1807 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1808 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1809 case Intrinsic::setjmp:
1810 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1811 break;
1812 case Intrinsic::longjmp:
1813 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1814 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001815 case Intrinsic::memcpy_i32:
1816 case Intrinsic::memcpy_i64:
1817 visitMemIntrinsic(I, ISD::MEMCPY);
1818 return 0;
1819 case Intrinsic::memset_i32:
1820 case Intrinsic::memset_i64:
1821 visitMemIntrinsic(I, ISD::MEMSET);
1822 return 0;
1823 case Intrinsic::memmove_i32:
1824 case Intrinsic::memmove_i64:
1825 visitMemIntrinsic(I, ISD::MEMMOVE);
1826 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001827
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001828 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001829 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001830 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001831 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001832 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001833
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001834 Ops[0] = getRoot();
1835 Ops[1] = getValue(SPI.getLineValue());
1836 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001837
Jim Laskeya8bdac82006-03-23 18:06:46 +00001838 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001839 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001840 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1841
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001842 Ops[3] = DAG.getString(CompileUnit->getFileName());
1843 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001844
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001845 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001846 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001847
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001848 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001849 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001850 case Intrinsic::dbg_region_start: {
1851 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1852 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001853 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001854 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001855 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1856 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001857 }
1858
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001859 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001860 }
1861 case Intrinsic::dbg_region_end: {
1862 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1863 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001864 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001865 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001866 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1867 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001868 }
1869
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001870 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001871 }
1872 case Intrinsic::dbg_func_start: {
1873 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1874 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001875 if (DebugInfo && FSI.getSubprogram() &&
1876 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001877 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001878 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1879 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001880 }
1881
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001882 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001883 }
1884 case Intrinsic::dbg_declare: {
1885 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1886 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001887 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001888 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001889 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001890 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001891 }
1892
1893 return 0;
1894 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001895
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001896 case Intrinsic::isunordered_f32:
1897 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001898 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1899 getValue(I.getOperand(2)), ISD::SETUO));
1900 return 0;
1901
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001902 case Intrinsic::sqrt_f32:
1903 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001904 setValue(&I, DAG.getNode(ISD::FSQRT,
1905 getValue(I.getOperand(1)).getValueType(),
1906 getValue(I.getOperand(1))));
1907 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001908 case Intrinsic::powi_f32:
1909 case Intrinsic::powi_f64:
1910 setValue(&I, DAG.getNode(ISD::FPOWI,
1911 getValue(I.getOperand(1)).getValueType(),
1912 getValue(I.getOperand(1)),
1913 getValue(I.getOperand(2))));
1914 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001915 case Intrinsic::pcmarker: {
1916 SDOperand Tmp = getValue(I.getOperand(1));
1917 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1918 return 0;
1919 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001920 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001921 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001922 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1923 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1924 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001925 setValue(&I, Tmp);
1926 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001927 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001928 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001929 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001930 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001931 case Intrinsic::bswap_i64:
1932 setValue(&I, DAG.getNode(ISD::BSWAP,
1933 getValue(I.getOperand(1)).getValueType(),
1934 getValue(I.getOperand(1))));
1935 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001936 case Intrinsic::cttz_i8:
1937 case Intrinsic::cttz_i16:
1938 case Intrinsic::cttz_i32:
1939 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001940 setValue(&I, DAG.getNode(ISD::CTTZ,
1941 getValue(I.getOperand(1)).getValueType(),
1942 getValue(I.getOperand(1))));
1943 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001944 case Intrinsic::ctlz_i8:
1945 case Intrinsic::ctlz_i16:
1946 case Intrinsic::ctlz_i32:
1947 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001948 setValue(&I, DAG.getNode(ISD::CTLZ,
1949 getValue(I.getOperand(1)).getValueType(),
1950 getValue(I.getOperand(1))));
1951 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001952 case Intrinsic::ctpop_i8:
1953 case Intrinsic::ctpop_i16:
1954 case Intrinsic::ctpop_i32:
1955 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001956 setValue(&I, DAG.getNode(ISD::CTPOP,
1957 getValue(I.getOperand(1)).getValueType(),
1958 getValue(I.getOperand(1))));
1959 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001960 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001961 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001962 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1963 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001964 setValue(&I, Tmp);
1965 DAG.setRoot(Tmp.getValue(1));
1966 return 0;
1967 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001968 case Intrinsic::stackrestore: {
1969 SDOperand Tmp = getValue(I.getOperand(1));
1970 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001971 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001972 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001973 case Intrinsic::prefetch:
1974 // FIXME: Currently discarding prefetches.
1975 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001976 }
1977}
1978
1979
Chris Lattner7a60d912005-01-07 07:47:53 +00001980void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001981 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001982 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001983 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001984 if (unsigned IID = F->getIntrinsicID()) {
1985 RenameFn = visitIntrinsicCall(I, IID);
1986 if (!RenameFn)
1987 return;
1988 } else { // Not an LLVM intrinsic.
1989 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001990 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1991 if (I.getNumOperands() == 3 && // Basic sanity checks.
1992 I.getOperand(1)->getType()->isFloatingPoint() &&
1993 I.getType() == I.getOperand(1)->getType() &&
1994 I.getType() == I.getOperand(2)->getType()) {
1995 SDOperand LHS = getValue(I.getOperand(1));
1996 SDOperand RHS = getValue(I.getOperand(2));
1997 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1998 LHS, RHS));
1999 return;
2000 }
2001 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002002 if (I.getNumOperands() == 2 && // Basic sanity checks.
2003 I.getOperand(1)->getType()->isFloatingPoint() &&
2004 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002005 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002006 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2007 return;
2008 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002009 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002010 if (I.getNumOperands() == 2 && // Basic sanity checks.
2011 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002012 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002013 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002014 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2015 return;
2016 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002017 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002018 if (I.getNumOperands() == 2 && // Basic sanity checks.
2019 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002020 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002021 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002022 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2023 return;
2024 }
2025 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002026 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002027 } else if (isa<InlineAsm>(I.getOperand(0))) {
2028 visitInlineAsm(I);
2029 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002030 }
Misha Brukman835702a2005-04-21 22:36:52 +00002031
Chris Lattner18d2b342005-01-08 22:48:57 +00002032 SDOperand Callee;
2033 if (!RenameFn)
2034 Callee = getValue(I.getOperand(0));
2035 else
2036 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002037 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002038 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002039 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2040 Value *Arg = I.getOperand(i);
2041 SDOperand ArgNode = getValue(Arg);
2042 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2043 }
Misha Brukman835702a2005-04-21 22:36:52 +00002044
Nate Begemanf6565252005-03-26 01:29:23 +00002045 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2046 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002047
Chris Lattner1f45cd72005-01-08 19:26:18 +00002048 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002049 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002050 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002051 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002052 setValue(&I, Result.first);
2053 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002054}
2055
Chris Lattner6f87d182006-02-22 22:37:12 +00002056SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002057 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002058 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2059 Chain = Val.getValue(1);
2060 Flag = Val.getValue(2);
2061
2062 // If the result was expanded, copy from the top part.
2063 if (Regs.size() > 1) {
2064 assert(Regs.size() == 2 &&
2065 "Cannot expand to more than 2 elts yet!");
2066 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002067 Chain = Hi.getValue(1);
2068 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002069 if (DAG.getTargetLoweringInfo().isLittleEndian())
2070 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2071 else
2072 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002073 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002074
Chris Lattner705948d2006-06-08 18:22:48 +00002075 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002076 // appropriate type.
2077 if (RegVT == ValueVT)
2078 return Val;
2079
Chris Lattner705948d2006-06-08 18:22:48 +00002080 if (MVT::isInteger(RegVT)) {
2081 if (ValueVT < RegVT)
2082 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2083 else
2084 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2085 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002086 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002087 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002088}
2089
Chris Lattner571d9642006-02-23 19:21:04 +00002090/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2091/// specified value into the registers specified by this object. This uses
2092/// Chain/Flag as the input and updates them for the output Chain/Flag.
2093void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002094 SDOperand &Chain, SDOperand &Flag,
2095 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002096 if (Regs.size() == 1) {
2097 // If there is a single register and the types differ, this must be
2098 // a promotion.
2099 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002100 if (MVT::isInteger(RegVT)) {
2101 if (RegVT < ValueVT)
2102 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2103 else
2104 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2105 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002106 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2107 }
2108 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2109 Flag = Chain.getValue(1);
2110 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002111 std::vector<unsigned> R(Regs);
2112 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2113 std::reverse(R.begin(), R.end());
2114
2115 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002116 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002117 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002118 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002119 Flag = Chain.getValue(1);
2120 }
2121 }
2122}
Chris Lattner6f87d182006-02-22 22:37:12 +00002123
Chris Lattner571d9642006-02-23 19:21:04 +00002124/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2125/// operand list. This adds the code marker and includes the number of
2126/// values added into it.
2127void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002128 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002129 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2130 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2131 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2132}
Chris Lattner6f87d182006-02-22 22:37:12 +00002133
2134/// isAllocatableRegister - If the specified register is safe to allocate,
2135/// i.e. it isn't a stack pointer or some other special register, return the
2136/// register class for the register. Otherwise, return null.
2137static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002138isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2139 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002140 MVT::ValueType FoundVT = MVT::Other;
2141 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002142 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2143 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002144 MVT::ValueType ThisVT = MVT::Other;
2145
Chris Lattnerb1124f32006-02-22 23:09:03 +00002146 const TargetRegisterClass *RC = *RCI;
2147 // If none of the the value types for this register class are valid, we
2148 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002149 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2150 I != E; ++I) {
2151 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002152 // If we have already found this register in a different register class,
2153 // choose the one with the largest VT specified. For example, on
2154 // PowerPC, we favor f64 register classes over f32.
2155 if (FoundVT == MVT::Other ||
2156 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2157 ThisVT = *I;
2158 break;
2159 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002160 }
2161 }
2162
Chris Lattnerbec582f2006-04-02 00:24:45 +00002163 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002164
Chris Lattner6f87d182006-02-22 22:37:12 +00002165 // NOTE: This isn't ideal. In particular, this might allocate the
2166 // frame pointer in functions that need it (due to them not being taken
2167 // out of allocation, because a variable sized allocation hasn't been seen
2168 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002169 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2170 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002171 if (*I == Reg) {
2172 // We found a matching register class. Keep looking at others in case
2173 // we find one with larger registers that this physreg is also in.
2174 FoundRC = RC;
2175 FoundVT = ThisVT;
2176 break;
2177 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002178 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002179 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002180}
2181
2182RegsForValue SelectionDAGLowering::
2183GetRegistersForValue(const std::string &ConstrCode,
2184 MVT::ValueType VT, bool isOutReg, bool isInReg,
2185 std::set<unsigned> &OutputRegs,
2186 std::set<unsigned> &InputRegs) {
2187 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2188 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2189 std::vector<unsigned> Regs;
2190
2191 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2192 MVT::ValueType RegVT;
2193 MVT::ValueType ValueVT = VT;
2194
2195 if (PhysReg.first) {
2196 if (VT == MVT::Other)
2197 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002198
2199 // Get the actual register value type. This is important, because the user
2200 // may have asked for (e.g.) the AX register in i32 type. We need to
2201 // remember that AX is actually i16 to get the right extension.
2202 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002203
2204 // This is a explicit reference to a physical register.
2205 Regs.push_back(PhysReg.first);
2206
2207 // If this is an expanded reference, add the rest of the regs to Regs.
2208 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002209 TargetRegisterClass::iterator I = PhysReg.second->begin();
2210 TargetRegisterClass::iterator E = PhysReg.second->end();
2211 for (; *I != PhysReg.first; ++I)
2212 assert(I != E && "Didn't find reg!");
2213
2214 // Already added the first reg.
2215 --NumRegs; ++I;
2216 for (; NumRegs; --NumRegs, ++I) {
2217 assert(I != E && "Ran out of registers to allocate!");
2218 Regs.push_back(*I);
2219 }
2220 }
2221 return RegsForValue(Regs, RegVT, ValueVT);
2222 }
2223
2224 // This is a reference to a register class. Allocate NumRegs consecutive,
2225 // available, registers from the class.
2226 std::vector<unsigned> RegClassRegs =
2227 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2228
2229 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2230 MachineFunction &MF = *CurMBB->getParent();
2231 unsigned NumAllocated = 0;
2232 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2233 unsigned Reg = RegClassRegs[i];
2234 // See if this register is available.
2235 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2236 (isInReg && InputRegs.count(Reg))) { // Already used.
2237 // Make sure we find consecutive registers.
2238 NumAllocated = 0;
2239 continue;
2240 }
2241
2242 // Check to see if this register is allocatable (i.e. don't give out the
2243 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002244 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002245 if (!RC) {
2246 // Make sure we find consecutive registers.
2247 NumAllocated = 0;
2248 continue;
2249 }
2250
2251 // Okay, this register is good, we can use it.
2252 ++NumAllocated;
2253
2254 // If we allocated enough consecutive
2255 if (NumAllocated == NumRegs) {
2256 unsigned RegStart = (i-NumAllocated)+1;
2257 unsigned RegEnd = i+1;
2258 // Mark all of the allocated registers used.
2259 for (unsigned i = RegStart; i != RegEnd; ++i) {
2260 unsigned Reg = RegClassRegs[i];
2261 Regs.push_back(Reg);
2262 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2263 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2264 }
2265
2266 return RegsForValue(Regs, *RC->vt_begin(), VT);
2267 }
2268 }
2269
2270 // Otherwise, we couldn't allocate enough registers for this.
2271 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002272}
2273
Chris Lattner6f87d182006-02-22 22:37:12 +00002274
Chris Lattner476e67b2006-01-26 22:24:51 +00002275/// visitInlineAsm - Handle a call to an InlineAsm object.
2276///
2277void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2278 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2279
2280 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2281 MVT::Other);
2282
2283 // Note, we treat inline asms both with and without side-effects as the same.
2284 // If an inline asm doesn't have side effects and doesn't access memory, we
2285 // could not choose to not chain it.
2286 bool hasSideEffects = IA->hasSideEffects();
2287
Chris Lattner3a5ed552006-02-01 01:28:23 +00002288 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002289 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002290
2291 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2292 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2293 /// if it is a def of that register.
2294 std::vector<SDOperand> AsmNodeOperands;
2295 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2296 AsmNodeOperands.push_back(AsmStr);
2297
2298 SDOperand Chain = getRoot();
2299 SDOperand Flag;
2300
Chris Lattner1558fc62006-02-01 18:59:47 +00002301 // We fully assign registers here at isel time. This is not optimal, but
2302 // should work. For register classes that correspond to LLVM classes, we
2303 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2304 // over the constraints, collecting fixed registers that we know we can't use.
2305 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002306 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002307 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2308 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2309 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002310
Chris Lattner7ad77df2006-02-22 00:56:39 +00002311 MVT::ValueType OpVT;
2312
2313 // Compute the value type for each operand and add it to ConstraintVTs.
2314 switch (Constraints[i].Type) {
2315 case InlineAsm::isOutput:
2316 if (!Constraints[i].isIndirectOutput) {
2317 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2318 OpVT = TLI.getValueType(I.getType());
2319 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002320 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002321 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2322 OpNum++; // Consumes a call operand.
2323 }
2324 break;
2325 case InlineAsm::isInput:
2326 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2327 OpNum++; // Consumes a call operand.
2328 break;
2329 case InlineAsm::isClobber:
2330 OpVT = MVT::Other;
2331 break;
2332 }
2333
2334 ConstraintVTs.push_back(OpVT);
2335
Chris Lattner6f87d182006-02-22 22:37:12 +00002336 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2337 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002338
Chris Lattner6f87d182006-02-22 22:37:12 +00002339 // Build a list of regs that this operand uses. This always has a single
2340 // element for promoted/expanded operands.
2341 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2342 false, false,
2343 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002344
2345 switch (Constraints[i].Type) {
2346 case InlineAsm::isOutput:
2347 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002348 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002349 // If this is an early-clobber output, it cannot be assigned to the same
2350 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002351 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002352 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002353 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002354 case InlineAsm::isInput:
2355 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002356 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002357 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002358 case InlineAsm::isClobber:
2359 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002360 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2361 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002362 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002363 }
2364 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002365
Chris Lattner5c79f982006-02-21 23:12:12 +00002366 // Loop over all of the inputs, copying the operand values into the
2367 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002368 RegsForValue RetValRegs;
2369 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002370 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002371
Chris Lattner2e56e892006-01-31 02:03:41 +00002372 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002373 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2374 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002375
Chris Lattner3a5ed552006-02-01 01:28:23 +00002376 switch (Constraints[i].Type) {
2377 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002378 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2379 if (ConstraintCode.size() == 1) // not a physreg name.
2380 CTy = TLI.getConstraintType(ConstraintCode[0]);
2381
2382 if (CTy == TargetLowering::C_Memory) {
2383 // Memory output.
2384 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2385
2386 // Check that the operand (the address to store to) isn't a float.
2387 if (!MVT::isInteger(InOperandVal.getValueType()))
2388 assert(0 && "MATCH FAIL!");
2389
2390 if (!Constraints[i].isIndirectOutput)
2391 assert(0 && "MATCH FAIL!");
2392
2393 OpNum++; // Consumes a call operand.
2394
2395 // Extend/truncate to the right pointer type if needed.
2396 MVT::ValueType PtrType = TLI.getPointerTy();
2397 if (InOperandVal.getValueType() < PtrType)
2398 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2399 else if (InOperandVal.getValueType() > PtrType)
2400 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2401
2402 // Add information to the INLINEASM node to know about this output.
2403 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2404 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2405 AsmNodeOperands.push_back(InOperandVal);
2406 break;
2407 }
2408
2409 // Otherwise, this is a register output.
2410 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2411
Chris Lattner6f87d182006-02-22 22:37:12 +00002412 // If this is an early-clobber output, or if there is an input
2413 // constraint that matches this, we need to reserve the input register
2414 // so no other inputs allocate to it.
2415 bool UsesInputRegister = false;
2416 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2417 UsesInputRegister = true;
2418
2419 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002420 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002421 RegsForValue Regs =
2422 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2423 true, UsesInputRegister,
2424 OutputRegs, InputRegs);
2425 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002426
Chris Lattner3a5ed552006-02-01 01:28:23 +00002427 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002428 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002429 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002430 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002431 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002432 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002433 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2434 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002435 OpNum++; // Consumes a call operand.
2436 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002437
2438 // Add information to the INLINEASM node to know that this register is
2439 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002440 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002441 break;
2442 }
2443 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002444 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002445 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002446
Chris Lattner7f5880b2006-02-02 00:25:23 +00002447 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2448 // If this is required to match an output register we have already set,
2449 // just use its register.
2450 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002451
Chris Lattner571d9642006-02-23 19:21:04 +00002452 // Scan until we find the definition we already emitted of this operand.
2453 // When we find it, create a RegsForValue operand.
2454 unsigned CurOp = 2; // The first operand.
2455 for (; OperandNo; --OperandNo) {
2456 // Advance to the next operand.
2457 unsigned NumOps =
2458 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002459 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2460 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002461 "Skipped past definitions?");
2462 CurOp += (NumOps>>3)+1;
2463 }
2464
2465 unsigned NumOps =
2466 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2467 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2468 "Skipped past definitions?");
2469
2470 // Add NumOps>>3 registers to MatchedRegs.
2471 RegsForValue MatchedRegs;
2472 MatchedRegs.ValueVT = InOperandVal.getValueType();
2473 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2474 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2475 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2476 MatchedRegs.Regs.push_back(Reg);
2477 }
2478
2479 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002480 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2481 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002482 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002483 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002484 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002485
2486 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2487 if (ConstraintCode.size() == 1) // not a physreg name.
2488 CTy = TLI.getConstraintType(ConstraintCode[0]);
2489
2490 if (CTy == TargetLowering::C_Other) {
2491 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2492 assert(0 && "MATCH FAIL!");
2493
2494 // Add information to the INLINEASM node to know about this input.
2495 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2496 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2497 AsmNodeOperands.push_back(InOperandVal);
2498 break;
2499 } else if (CTy == TargetLowering::C_Memory) {
2500 // Memory input.
2501
2502 // Check that the operand isn't a float.
2503 if (!MVT::isInteger(InOperandVal.getValueType()))
2504 assert(0 && "MATCH FAIL!");
2505
2506 // Extend/truncate to the right pointer type if needed.
2507 MVT::ValueType PtrType = TLI.getPointerTy();
2508 if (InOperandVal.getValueType() < PtrType)
2509 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2510 else if (InOperandVal.getValueType() > PtrType)
2511 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2512
2513 // Add information to the INLINEASM node to know about this input.
2514 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2515 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2516 AsmNodeOperands.push_back(InOperandVal);
2517 break;
2518 }
2519
2520 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2521
2522 // Copy the input into the appropriate registers.
2523 RegsForValue InRegs =
2524 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2525 false, true, OutputRegs, InputRegs);
2526 // FIXME: should be match fail.
2527 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2528
Evan Chengef9e07d2006-06-15 08:11:54 +00002529 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002530
2531 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002532 break;
2533 }
Chris Lattner571d9642006-02-23 19:21:04 +00002534 case InlineAsm::isClobber: {
2535 RegsForValue ClobberedRegs =
2536 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2537 OutputRegs, InputRegs);
2538 // Add the clobbered value to the operand list, so that the register
2539 // allocator is aware that the physreg got clobbered.
2540 if (!ClobberedRegs.Regs.empty())
2541 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002542 break;
2543 }
Chris Lattner571d9642006-02-23 19:21:04 +00002544 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002545 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002546
2547 // Finish up input operands.
2548 AsmNodeOperands[0] = Chain;
2549 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2550
Chris Lattnerbd887772006-08-14 23:53:35 +00002551 Chain = DAG.getNode(ISD::INLINEASM,
2552 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002553 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002554 Flag = Chain.getValue(1);
2555
Chris Lattner2e56e892006-01-31 02:03:41 +00002556 // If this asm returns a register value, copy the result from that register
2557 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002558 if (!RetValRegs.Regs.empty())
2559 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002560
Chris Lattner2e56e892006-01-31 02:03:41 +00002561 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2562
2563 // Process indirect outputs, first output all of the flagged copies out of
2564 // physregs.
2565 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002566 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002567 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002568 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2569 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002570 }
2571
2572 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002573 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002574 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002575 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002576 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002577 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002578 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002579 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2580 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002581 DAG.setRoot(Chain);
2582}
2583
2584
Chris Lattner7a60d912005-01-07 07:47:53 +00002585void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2586 SDOperand Src = getValue(I.getOperand(0));
2587
2588 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002589
2590 if (IntPtr < Src.getValueType())
2591 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2592 else if (IntPtr > Src.getValueType())
2593 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002594
2595 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002596 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002597 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2598 Src, getIntPtrConstant(ElementSize));
2599
2600 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002601 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002602
2603 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002604 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002605 DAG.getExternalSymbol("malloc", IntPtr),
2606 Args, DAG);
2607 setValue(&I, Result.first); // Pointers always fit in registers
2608 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002609}
2610
2611void SelectionDAGLowering::visitFree(FreeInst &I) {
2612 std::vector<std::pair<SDOperand, const Type*> > Args;
2613 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002614 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002615 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002616 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002617 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002618 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2619 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002620}
2621
Chris Lattner13d7c252005-08-26 20:54:47 +00002622// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2623// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2624// instructions are special in various ways, which require special support to
2625// insert. The specified MachineInstr is created but not inserted into any
2626// basic blocks, and the scheduler passes ownership of it to this method.
2627MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2628 MachineBasicBlock *MBB) {
2629 std::cerr << "If a target marks an instruction with "
2630 "'usesCustomDAGSchedInserter', it must implement "
2631 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2632 abort();
2633 return 0;
2634}
2635
Chris Lattner58cfd792005-01-09 00:00:49 +00002636void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002637 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2638 getValue(I.getOperand(1)),
2639 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002640}
2641
2642void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002643 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2644 getValue(I.getOperand(0)),
2645 DAG.getSrcValue(I.getOperand(0)));
2646 setValue(&I, V);
2647 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002648}
2649
2650void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002651 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2652 getValue(I.getOperand(1)),
2653 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002654}
2655
2656void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002657 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2658 getValue(I.getOperand(1)),
2659 getValue(I.getOperand(2)),
2660 DAG.getSrcValue(I.getOperand(1)),
2661 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002662}
2663
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002664/// TargetLowering::LowerArguments - This is the default LowerArguments
2665/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002666/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2667/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002668std::vector<SDOperand>
2669TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2670 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2671 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002672 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002673 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2674 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2675
2676 // Add one result value for each formal argument.
2677 std::vector<MVT::ValueType> RetVals;
2678 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2679 MVT::ValueType VT = getValueType(I->getType());
2680
2681 switch (getTypeAction(VT)) {
2682 default: assert(0 && "Unknown type action!");
2683 case Legal:
2684 RetVals.push_back(VT);
2685 break;
2686 case Promote:
2687 RetVals.push_back(getTypeToTransformTo(VT));
2688 break;
2689 case Expand:
2690 if (VT != MVT::Vector) {
2691 // If this is a large integer, it needs to be broken up into small
2692 // integers. Figure out what the destination type is and how many small
2693 // integers it turns into.
2694 MVT::ValueType NVT = getTypeToTransformTo(VT);
2695 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2696 for (unsigned i = 0; i != NumVals; ++i)
2697 RetVals.push_back(NVT);
2698 } else {
2699 // Otherwise, this is a vector type. We only support legal vectors
2700 // right now.
2701 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2702 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002703
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002704 // Figure out if there is a Packed type corresponding to this Vector
2705 // type. If so, convert to the packed type.
2706 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2707 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2708 RetVals.push_back(TVT);
2709 } else {
2710 assert(0 && "Don't support illegal by-val vector arguments yet!");
2711 }
2712 }
2713 break;
2714 }
2715 }
Evan Cheng9618df12006-04-25 23:03:35 +00002716
Chris Lattner3d826992006-05-16 06:45:34 +00002717 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002718
2719 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002720 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2721 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002722 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002723
2724 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002725
2726 // Set up the return result vector.
2727 Ops.clear();
2728 unsigned i = 0;
2729 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2730 MVT::ValueType VT = getValueType(I->getType());
2731
2732 switch (getTypeAction(VT)) {
2733 default: assert(0 && "Unknown type action!");
2734 case Legal:
2735 Ops.push_back(SDOperand(Result, i++));
2736 break;
2737 case Promote: {
2738 SDOperand Op(Result, i++);
2739 if (MVT::isInteger(VT)) {
2740 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2741 : ISD::AssertZext;
2742 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2743 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2744 } else {
2745 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2746 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2747 }
2748 Ops.push_back(Op);
2749 break;
2750 }
2751 case Expand:
2752 if (VT != MVT::Vector) {
2753 // If this is a large integer, it needs to be reassembled from small
2754 // integers. Figure out what the source elt type is and how many small
2755 // integers it is.
2756 MVT::ValueType NVT = getTypeToTransformTo(VT);
2757 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2758 if (NumVals == 2) {
2759 SDOperand Lo = SDOperand(Result, i++);
2760 SDOperand Hi = SDOperand(Result, i++);
2761
2762 if (!isLittleEndian())
2763 std::swap(Lo, Hi);
2764
2765 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2766 } else {
2767 // Value scalarized into many values. Unimp for now.
2768 assert(0 && "Cannot expand i64 -> i16 yet!");
2769 }
2770 } else {
2771 // Otherwise, this is a vector type. We only support legal vectors
2772 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002773 const PackedType *PTy = cast<PackedType>(I->getType());
2774 unsigned NumElems = PTy->getNumElements();
2775 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002776
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002777 // Figure out if there is a Packed type corresponding to this Vector
2778 // type. If so, convert to the packed type.
2779 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002780 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002781 SDOperand N = SDOperand(Result, i++);
2782 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002783 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2784 DAG.getConstant(NumElems, MVT::i32),
2785 DAG.getValueType(getValueType(EltTy)));
2786 Ops.push_back(N);
2787 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002788 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002789 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002790 }
2791 }
2792 break;
2793 }
2794 }
2795 return Ops;
2796}
2797
Chris Lattneraaa23d92006-05-16 22:53:20 +00002798
2799/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2800/// implementation, which just inserts an ISD::CALL node, which is later custom
2801/// lowered by the target to something concrete. FIXME: When all targets are
2802/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2803std::pair<SDOperand, SDOperand>
2804TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2805 unsigned CallingConv, bool isTailCall,
2806 SDOperand Callee,
2807 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002808 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002809 Ops.push_back(Chain); // Op#0 - Chain
2810 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2811 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2812 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2813 Ops.push_back(Callee);
2814
2815 // Handle all of the outgoing arguments.
2816 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2817 MVT::ValueType VT = getValueType(Args[i].second);
2818 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002819 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002820 switch (getTypeAction(VT)) {
2821 default: assert(0 && "Unknown type action!");
2822 case Legal:
2823 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002824 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002825 break;
2826 case Promote:
2827 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002828 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002829 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2830 } else {
2831 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2832 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2833 }
2834 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002835 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002836 break;
2837 case Expand:
2838 if (VT != MVT::Vector) {
2839 // If this is a large integer, it needs to be broken down into small
2840 // integers. Figure out what the source elt type is and how many small
2841 // integers it is.
2842 MVT::ValueType NVT = getTypeToTransformTo(VT);
2843 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2844 if (NumVals == 2) {
2845 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2846 DAG.getConstant(0, getPointerTy()));
2847 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2848 DAG.getConstant(1, getPointerTy()));
2849 if (!isLittleEndian())
2850 std::swap(Lo, Hi);
2851
2852 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002853 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002854 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002855 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002856 } else {
2857 // Value scalarized into many values. Unimp for now.
2858 assert(0 && "Cannot expand i64 -> i16 yet!");
2859 }
2860 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002861 // Otherwise, this is a vector type. We only support legal vectors
2862 // right now.
2863 const PackedType *PTy = cast<PackedType>(Args[i].second);
2864 unsigned NumElems = PTy->getNumElements();
2865 const Type *EltTy = PTy->getElementType();
2866
2867 // Figure out if there is a Packed type corresponding to this Vector
2868 // type. If so, convert to the packed type.
2869 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002870 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2871 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2872 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2873 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002874 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002875 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002876 assert(0 && "Don't support illegal by-val vector call args yet!");
2877 abort();
2878 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002879 }
2880 break;
2881 }
2882 }
2883
2884 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002885 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002886
2887 if (RetTy != Type::VoidTy) {
2888 MVT::ValueType VT = getValueType(RetTy);
2889 switch (getTypeAction(VT)) {
2890 default: assert(0 && "Unknown type action!");
2891 case Legal:
2892 RetTys.push_back(VT);
2893 break;
2894 case Promote:
2895 RetTys.push_back(getTypeToTransformTo(VT));
2896 break;
2897 case Expand:
2898 if (VT != MVT::Vector) {
2899 // If this is a large integer, it needs to be reassembled from small
2900 // integers. Figure out what the source elt type is and how many small
2901 // integers it is.
2902 MVT::ValueType NVT = getTypeToTransformTo(VT);
2903 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2904 for (unsigned i = 0; i != NumVals; ++i)
2905 RetTys.push_back(NVT);
2906 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002907 // Otherwise, this is a vector type. We only support legal vectors
2908 // right now.
2909 const PackedType *PTy = cast<PackedType>(RetTy);
2910 unsigned NumElems = PTy->getNumElements();
2911 const Type *EltTy = PTy->getElementType();
2912
2913 // Figure out if there is a Packed type corresponding to this Vector
2914 // type. If so, convert to the packed type.
2915 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2916 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2917 RetTys.push_back(TVT);
2918 } else {
2919 assert(0 && "Don't support illegal by-val vector call results yet!");
2920 abort();
2921 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002922 }
2923 }
2924 }
2925
2926 RetTys.push_back(MVT::Other); // Always has a chain.
2927
2928 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002929 SDOperand Res = DAG.getNode(ISD::CALL,
2930 DAG.getVTList(&RetTys[0], RetTys.size()),
2931 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002932
2933 // This returns a pair of operands. The first element is the
2934 // return value for the function (if RetTy is not VoidTy). The second
2935 // element is the outgoing token chain.
2936 SDOperand ResVal;
2937 if (RetTys.size() != 1) {
2938 MVT::ValueType VT = getValueType(RetTy);
2939 if (RetTys.size() == 2) {
2940 ResVal = Res;
2941
2942 // If this value was promoted, truncate it down.
2943 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002944 if (VT == MVT::Vector) {
2945 // Insert a VBITCONVERT to convert from the packed result type to the
2946 // MVT::Vector type.
2947 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2948 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2949
2950 // Figure out if there is a Packed type corresponding to this Vector
2951 // type. If so, convert to the packed type.
2952 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2953 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002954 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2955 // "N x PTyElementVT" MVT::Vector type.
2956 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002957 DAG.getConstant(NumElems, MVT::i32),
2958 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002959 } else {
2960 abort();
2961 }
2962 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002963 unsigned AssertOp = RetTy->isSigned() ?
2964 ISD::AssertSext : ISD::AssertZext;
2965 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2966 DAG.getValueType(VT));
2967 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2968 } else {
2969 assert(MVT::isFloatingPoint(VT));
2970 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2971 }
2972 }
2973 } else if (RetTys.size() == 3) {
2974 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2975 Res.getValue(0), Res.getValue(1));
2976
2977 } else {
2978 assert(0 && "Case not handled yet!");
2979 }
2980 }
2981
2982 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2983}
2984
2985
2986
Chris Lattner58cfd792005-01-09 00:00:49 +00002987// It is always conservatively correct for llvm.returnaddress and
2988// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002989//
2990// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2991// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002992std::pair<SDOperand, SDOperand>
2993TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2994 unsigned Depth, SelectionDAG &DAG) {
2995 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002996}
2997
Chris Lattner29dcc712005-05-14 05:50:48 +00002998SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002999 assert(0 && "LowerOperation not implemented for this target!");
3000 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003001 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003002}
3003
Nate Begeman595ec732006-01-28 03:14:31 +00003004SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3005 SelectionDAG &DAG) {
3006 assert(0 && "CustomPromoteOperation not implemented for this target!");
3007 abort();
3008 return SDOperand();
3009}
3010
Chris Lattner58cfd792005-01-09 00:00:49 +00003011void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003012 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00003013 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00003014 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00003015 setValue(&I, Result.first);
3016 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003017}
3018
Evan Cheng6781b6e2006-02-15 21:59:04 +00003019/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003020/// operand.
3021static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003022 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003023 MVT::ValueType CurVT = VT;
3024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3025 uint64_t Val = C->getValue() & 255;
3026 unsigned Shift = 8;
3027 while (CurVT != MVT::i8) {
3028 Val = (Val << Shift) | Val;
3029 Shift <<= 1;
3030 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003031 }
3032 return DAG.getConstant(Val, VT);
3033 } else {
3034 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3035 unsigned Shift = 8;
3036 while (CurVT != MVT::i8) {
3037 Value =
3038 DAG.getNode(ISD::OR, VT,
3039 DAG.getNode(ISD::SHL, VT, Value,
3040 DAG.getConstant(Shift, MVT::i8)), Value);
3041 Shift <<= 1;
3042 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003043 }
3044
3045 return Value;
3046 }
3047}
3048
Evan Cheng6781b6e2006-02-15 21:59:04 +00003049/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3050/// used when a memcpy is turned into a memset when the source is a constant
3051/// string ptr.
3052static SDOperand getMemsetStringVal(MVT::ValueType VT,
3053 SelectionDAG &DAG, TargetLowering &TLI,
3054 std::string &Str, unsigned Offset) {
3055 MVT::ValueType CurVT = VT;
3056 uint64_t Val = 0;
3057 unsigned MSB = getSizeInBits(VT) / 8;
3058 if (TLI.isLittleEndian())
3059 Offset = Offset + MSB - 1;
3060 for (unsigned i = 0; i != MSB; ++i) {
3061 Val = (Val << 8) | Str[Offset];
3062 Offset += TLI.isLittleEndian() ? -1 : 1;
3063 }
3064 return DAG.getConstant(Val, VT);
3065}
3066
Evan Cheng81fcea82006-02-14 08:22:34 +00003067/// getMemBasePlusOffset - Returns base and offset node for the
3068static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3069 SelectionDAG &DAG, TargetLowering &TLI) {
3070 MVT::ValueType VT = Base.getValueType();
3071 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3072}
3073
Evan Chengdb2a7a72006-02-14 20:12:38 +00003074/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003075/// to replace the memset / memcpy is below the threshold. It also returns the
3076/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003077static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3078 unsigned Limit, uint64_t Size,
3079 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003080 MVT::ValueType VT;
3081
3082 if (TLI.allowsUnalignedMemoryAccesses()) {
3083 VT = MVT::i64;
3084 } else {
3085 switch (Align & 7) {
3086 case 0:
3087 VT = MVT::i64;
3088 break;
3089 case 4:
3090 VT = MVT::i32;
3091 break;
3092 case 2:
3093 VT = MVT::i16;
3094 break;
3095 default:
3096 VT = MVT::i8;
3097 break;
3098 }
3099 }
3100
Evan Chengd5026102006-02-14 09:11:59 +00003101 MVT::ValueType LVT = MVT::i64;
3102 while (!TLI.isTypeLegal(LVT))
3103 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3104 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003105
Evan Chengd5026102006-02-14 09:11:59 +00003106 if (VT > LVT)
3107 VT = LVT;
3108
Evan Cheng04514992006-02-14 23:05:54 +00003109 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003110 while (Size != 0) {
3111 unsigned VTSize = getSizeInBits(VT) / 8;
3112 while (VTSize > Size) {
3113 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003114 VTSize >>= 1;
3115 }
Evan Chengd5026102006-02-14 09:11:59 +00003116 assert(MVT::isInteger(VT));
3117
3118 if (++NumMemOps > Limit)
3119 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003120 MemOps.push_back(VT);
3121 Size -= VTSize;
3122 }
Evan Chengd5026102006-02-14 09:11:59 +00003123
3124 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003125}
3126
Chris Lattner875def92005-01-11 05:56:49 +00003127void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003128 SDOperand Op1 = getValue(I.getOperand(1));
3129 SDOperand Op2 = getValue(I.getOperand(2));
3130 SDOperand Op3 = getValue(I.getOperand(3));
3131 SDOperand Op4 = getValue(I.getOperand(4));
3132 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3133 if (Align == 0) Align = 1;
3134
3135 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3136 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003137
3138 // Expand memset / memcpy to a series of load / store ops
3139 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003140 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003141 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003142 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003143 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003144 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3145 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003146 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003147 unsigned Offset = 0;
3148 for (unsigned i = 0; i < NumMemOps; i++) {
3149 MVT::ValueType VT = MemOps[i];
3150 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003151 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003152 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003153 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003154 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003155 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003156 Offset += VTSize;
3157 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003158 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003159 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003160 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003161 case ISD::MEMCPY: {
3162 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3163 Size->getValue(), Align, TLI)) {
3164 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003165 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003166 GlobalAddressSDNode *G = NULL;
3167 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003168 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003169
3170 if (Op2.getOpcode() == ISD::GlobalAddress)
3171 G = cast<GlobalAddressSDNode>(Op2);
3172 else if (Op2.getOpcode() == ISD::ADD &&
3173 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3174 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3175 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003176 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003177 }
3178 if (G) {
3179 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003180 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00003181 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003182 if (!Str.empty()) {
3183 CopyFromStr = true;
3184 SrcOff += SrcDelta;
3185 }
3186 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003187 }
3188
Evan Chenge2038bd2006-02-15 01:54:51 +00003189 for (unsigned i = 0; i < NumMemOps; i++) {
3190 MVT::ValueType VT = MemOps[i];
3191 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003192 SDOperand Value, Chain, Store;
3193
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003194 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003195 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3196 Chain = getRoot();
3197 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003198 DAG.getStore(Chain, Value,
3199 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003200 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003201 } else {
3202 Value = DAG.getLoad(VT, getRoot(),
3203 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003204 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003205 Chain = Value.getValue(1);
3206 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003207 DAG.getStore(Chain, Value,
3208 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003209 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003210 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003211 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003212 SrcOff += VTSize;
3213 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003214 }
3215 }
3216 break;
3217 }
3218 }
3219
3220 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003221 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3222 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003223 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003224 }
3225 }
3226
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003227 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003228}
3229
Chris Lattner875def92005-01-11 05:56:49 +00003230//===----------------------------------------------------------------------===//
3231// SelectionDAGISel code
3232//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003233
3234unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3235 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3236}
3237
Chris Lattnerc9950c12005-08-17 06:37:43 +00003238void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003239 // FIXME: we only modify the CFG to split critical edges. This
3240 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003241 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003242}
Chris Lattner7a60d912005-01-07 07:47:53 +00003243
Chris Lattner35397782005-12-05 07:10:48 +00003244
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003245/// OptimizeNoopCopyExpression - We have determined that the specified cast
3246/// instruction is a noop copy (e.g. it's casting from one pointer type to
3247/// another, int->uint, or int->sbyte on PPC.
3248///
3249/// Return true if any changes are made.
3250static bool OptimizeNoopCopyExpression(CastInst *CI) {
3251 BasicBlock *DefBB = CI->getParent();
3252
3253 /// InsertedCasts - Only insert a cast in each block once.
3254 std::map<BasicBlock*, CastInst*> InsertedCasts;
3255
3256 bool MadeChange = false;
3257 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3258 UI != E; ) {
3259 Use &TheUse = UI.getUse();
3260 Instruction *User = cast<Instruction>(*UI);
3261
3262 // Figure out which BB this cast is used in. For PHI's this is the
3263 // appropriate predecessor block.
3264 BasicBlock *UserBB = User->getParent();
3265 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3266 unsigned OpVal = UI.getOperandNo()/2;
3267 UserBB = PN->getIncomingBlock(OpVal);
3268 }
3269
3270 // Preincrement use iterator so we don't invalidate it.
3271 ++UI;
3272
3273 // If this user is in the same block as the cast, don't change the cast.
3274 if (UserBB == DefBB) continue;
3275
3276 // If we have already inserted a cast into this block, use it.
3277 CastInst *&InsertedCast = InsertedCasts[UserBB];
3278
3279 if (!InsertedCast) {
3280 BasicBlock::iterator InsertPt = UserBB->begin();
3281 while (isa<PHINode>(InsertPt)) ++InsertPt;
3282
3283 InsertedCast =
3284 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3285 MadeChange = true;
3286 }
3287
3288 // Replace a use of the cast with a use of the new casat.
3289 TheUse = InsertedCast;
3290 }
3291
3292 // If we removed all uses, nuke the cast.
3293 if (CI->use_empty())
3294 CI->eraseFromParent();
3295
3296 return MadeChange;
3297}
3298
Chris Lattner35397782005-12-05 07:10:48 +00003299/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3300/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003301static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3302 Instruction *GEPI, Value *Ptr,
3303 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003304 if (V) return V; // Already computed.
3305
3306 BasicBlock::iterator InsertPt;
3307 if (BB == GEPI->getParent()) {
3308 // If insert into the GEP's block, insert right after the GEP.
3309 InsertPt = GEPI;
3310 ++InsertPt;
3311 } else {
3312 // Otherwise, insert at the top of BB, after any PHI nodes
3313 InsertPt = BB->begin();
3314 while (isa<PHINode>(InsertPt)) ++InsertPt;
3315 }
3316
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003317 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3318 // BB so that there is only one value live across basic blocks (the cast
3319 // operand).
3320 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3321 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3322 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3323
Chris Lattner35397782005-12-05 07:10:48 +00003324 // Add the offset, cast it to the right type.
3325 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003326 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003327}
3328
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003329/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3330/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3331/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3332/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3333/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3334/// the constant add into a load or store instruction. Additionally, if a user
3335/// is a pointer-pointer cast, we look through it to find its users.
3336static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3337 Constant *PtrOffset, BasicBlock *DefBB,
3338 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003339 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003340 while (!RepPtr->use_empty()) {
3341 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003342
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003343 // If the user is a Pointer-Pointer cast, recurse.
3344 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3345 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003346
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003347 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3348 // could invalidate an iterator.
3349 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3350 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003351 }
3352
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003353 // If this is a load of the pointer, or a store through the pointer, emit
3354 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003355 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003356 if (isa<LoadInst>(User) ||
3357 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3358 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3359 User->getParent(), GEPI,
3360 Ptr, PtrOffset);
3361 } else {
3362 // If this use is not foldable into the addressing mode, use a version
3363 // emitted in the GEP block.
3364 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3365 Ptr, PtrOffset);
3366 }
3367
Chris Lattner21cd9902006-05-06 09:10:37 +00003368 if (GEPI->getType() != RepPtr->getType()) {
3369 BasicBlock::iterator IP = NewVal;
3370 ++IP;
3371 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3372 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003373 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003374 }
3375}
Chris Lattner35397782005-12-05 07:10:48 +00003376
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003377
Chris Lattner35397782005-12-05 07:10:48 +00003378/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3379/// selection, we want to be a bit careful about some things. In particular, if
3380/// we have a GEP instruction that is used in a different block than it is
3381/// defined, the addressing expression of the GEP cannot be folded into loads or
3382/// stores that use it. In this case, decompose the GEP and move constant
3383/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003384static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003385 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003386 // If this GEP is only used inside the block it is defined in, there is no
3387 // need to rewrite it.
3388 bool isUsedOutsideDefBB = false;
3389 BasicBlock *DefBB = GEPI->getParent();
3390 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3391 UI != E; ++UI) {
3392 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3393 isUsedOutsideDefBB = true;
3394 break;
3395 }
3396 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003397 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003398
3399 // If this GEP has no non-zero constant indices, there is nothing we can do,
3400 // ignore it.
3401 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003402 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003403 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3404 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003405 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003406 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003407 hasConstantIndex = true;
3408 break;
3409 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003410 } else {
3411 hasVariableIndex = true;
3412 }
Chris Lattner35397782005-12-05 07:10:48 +00003413 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003414
3415 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3416 if (!hasConstantIndex && !hasVariableIndex) {
3417 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3418 GEPI->getName(), GEPI);
3419 GEPI->replaceAllUsesWith(NC);
3420 GEPI->eraseFromParent();
3421 return true;
3422 }
3423
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003424 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003425 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3426 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003427
3428 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3429 // constant offset (which we now know is non-zero) and deal with it later.
3430 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003431 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003432 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3433 const Type *Ty = GEPI->getOperand(0)->getType();
3434
3435 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3436 E = GEPI->op_end(); OI != E; ++OI) {
3437 Value *Idx = *OI;
3438 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003439 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003440 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003441 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003442 Ty = StTy->getElementType(Field);
3443 } else {
3444 Ty = cast<SequentialType>(Ty)->getElementType();
3445
3446 // Handle constant subscripts.
3447 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003448 if (CI->getZExtValue() == 0) continue;
3449 if (CI->getType()->isSigned())
3450 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003451 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003452 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003453 continue;
3454 }
3455
3456 // Ptr = Ptr + Idx * ElementSize;
3457
3458 // Cast Idx to UIntPtrTy if needed.
3459 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3460
Owen Anderson20a631f2006-05-03 01:29:57 +00003461 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003462 // Mask off bits that should not be set.
3463 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003464 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003465
3466 // Multiply by the element size and add to the base.
3467 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3468 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3469 }
3470 }
3471
3472 // Make sure that the offset fits in uintptr_t.
3473 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003474 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003475
3476 // Okay, we have now emitted all of the variable index parts to the BB that
3477 // the GEP is defined in. Loop over all of the using instructions, inserting
3478 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003479 // instruction to use the newly computed value, making GEPI dead. When the
3480 // user is a load or store instruction address, we emit the add into the user
3481 // block, otherwise we use a canonical version right next to the gep (these
3482 // won't be foldable as addresses, so we might as well share the computation).
3483
Chris Lattner21cd9902006-05-06 09:10:37 +00003484 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003485 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003486
3487 // Finally, the GEP is dead, remove it.
3488 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003489
3490 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003491}
3492
Chris Lattner7a60d912005-01-07 07:47:53 +00003493bool SelectionDAGISel::runOnFunction(Function &Fn) {
3494 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3495 RegMap = MF.getSSARegMap();
3496 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3497
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003498 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003499 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003500 // In this pass we also look for GEP and cast instructions that are used
3501 // across basic blocks and rewrite them to improve basic-block-at-a-time
3502 // selection.
3503 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003504 bool MadeChange = true;
3505 while (MadeChange) {
3506 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003507 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003508 // Split all critical edges.
3509 TerminatorInst *BBTI = BB->getTerminator();
3510 if (BBTI->getNumSuccessors() > 1) {
3511 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3512 SplitCriticalEdge(BBTI, i, this, true);
3513 }
3514
Chris Lattner35397782005-12-05 07:10:48 +00003515
Chris Lattnera9caf952006-09-28 06:17:10 +00003516 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003517 Instruction *I = BBI++;
3518 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003519 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003520 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003521 // If the source of the cast is a constant, then this should have
3522 // already been constant folded. The only reason NOT to constant fold
3523 // it is if something (e.g. LSR) was careful to place the constant
3524 // evaluation in a block other than then one that uses it (e.g. to hoist
3525 // the address of globals out of a loop). If this is the case, we don't
3526 // want to forward-subst the cast.
3527 if (isa<Constant>(CI->getOperand(0)))
3528 continue;
3529
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003530 // If this is a noop copy, sink it into user blocks to reduce the number
3531 // of virtual registers that must be created and coallesced.
3532 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3533 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3534
3535 // This is an fp<->int conversion?
3536 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3537 continue;
3538
3539 // If this is an extension, it will be a zero or sign extension, which
3540 // isn't a noop.
3541 if (SrcVT < DstVT) continue;
3542
3543 // If these values will be promoted, find out what they will be promoted
3544 // to. This helps us consider truncates on PPC as noop copies when they
3545 // are.
3546 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3547 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3548 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3549 DstVT = TLI.getTypeToTransformTo(DstVT);
3550
3551 // If, after promotion, these are the same types, this is a noop copy.
3552 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003553 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003554 }
3555 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003556 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003557 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003558
Chris Lattner7a60d912005-01-07 07:47:53 +00003559 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3560
3561 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3562 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003563
Chris Lattner7a60d912005-01-07 07:47:53 +00003564 return true;
3565}
3566
Chris Lattnered0110b2006-10-27 21:36:01 +00003567SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3568 unsigned Reg) {
3569 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003570 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003571 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003572 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003573
3574 // If this type is not legal, we must make sure to not create an invalid
3575 // register use.
3576 MVT::ValueType SrcVT = Op.getValueType();
3577 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003578 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003579 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003580 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003581 // Handle copies from generic vectors to registers.
3582 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3583 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3584 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003585
Chris Lattner5fe1f542006-03-31 02:06:56 +00003586 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3587 // MVT::Vector type.
3588 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3589 DAG.getConstant(NE, MVT::i32),
3590 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003591
Chris Lattner5fe1f542006-03-31 02:06:56 +00003592 // Loop over all of the elements of the resultant vector,
3593 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3594 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003595 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003596 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003597 for (unsigned i = 0; i != NE; ++i) {
3598 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003599 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003600 if (PTyElementVT == PTyLegalElementVT) {
3601 // Elements are legal.
3602 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3603 } else if (PTyLegalElementVT > PTyElementVT) {
3604 // Elements are promoted.
3605 if (MVT::isFloatingPoint(PTyLegalElementVT))
3606 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3607 else
3608 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3609 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3610 } else {
3611 // Elements are expanded.
3612 // The src value is expanded into multiple registers.
3613 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003614 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003615 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003616 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003617 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3618 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3619 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003620 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003621 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3622 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003623 } else if (SrcVT < DestVT) {
3624 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003625 if (MVT::isFloatingPoint(SrcVT))
3626 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3627 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003628 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003629 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003630 } else {
3631 // The src value is expanded into multiple registers.
3632 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003633 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003634 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003635 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003636 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003637 return DAG.getCopyToReg(Op, Reg+1, Hi);
3638 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003639}
3640
Chris Lattner16f64df2005-01-17 17:15:02 +00003641void SelectionDAGISel::
3642LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3643 std::vector<SDOperand> &UnorderedChains) {
3644 // If this is the entry block, emit arguments.
3645 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003646 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003647 SDOperand OldRoot = SDL.DAG.getRoot();
3648 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003649
Chris Lattner6871b232005-10-30 19:42:35 +00003650 unsigned a = 0;
3651 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3652 AI != E; ++AI, ++a)
3653 if (!AI->use_empty()) {
3654 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003655
Chris Lattner6871b232005-10-30 19:42:35 +00003656 // If this argument is live outside of the entry block, insert a copy from
3657 // whereever we got it to the vreg that other BB's will reference it as.
3658 if (FuncInfo.ValueMap.count(AI)) {
3659 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003660 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003661 UnorderedChains.push_back(Copy);
3662 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003663 }
Chris Lattner6871b232005-10-30 19:42:35 +00003664
Chris Lattner6871b232005-10-30 19:42:35 +00003665 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003666 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003667 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003668}
3669
Chris Lattner7a60d912005-01-07 07:47:53 +00003670void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3671 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003672 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003673 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003674
3675 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003676
Chris Lattner6871b232005-10-30 19:42:35 +00003677 // Lower any arguments needed in this block if this is the entry block.
3678 if (LLVMBB == &LLVMBB->getParent()->front())
3679 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003680
3681 BB = FuncInfo.MBBMap[LLVMBB];
3682 SDL.setCurrentBasicBlock(BB);
3683
3684 // Lower all of the non-terminator instructions.
3685 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3686 I != E; ++I)
3687 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003688
Chris Lattner7a60d912005-01-07 07:47:53 +00003689 // Ensure that all instructions which are used outside of their defining
3690 // blocks are available as virtual registers.
3691 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003692 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003693 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003694 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003695 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003696 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003697 }
3698
3699 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3700 // ensure constants are generated when needed. Remember the virtual registers
3701 // that need to be added to the Machine PHI nodes as input. We cannot just
3702 // directly add them, because expansion might result in multiple MBB's for one
3703 // BB. As such, the start of the BB might correspond to a different MBB than
3704 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003705 //
Chris Lattner84a03502006-10-27 23:50:33 +00003706 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00003707
3708 // Emit constants only once even if used by multiple PHI nodes.
3709 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003710
Chris Lattner84a03502006-10-27 23:50:33 +00003711 // Vector bool would be better, but vector<bool> is really slow.
3712 std::vector<unsigned char> SuccsHandled;
3713 if (TI->getNumSuccessors())
3714 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3715
Chris Lattner7a60d912005-01-07 07:47:53 +00003716 // Check successor nodes PHI nodes that expect a constant to be available from
3717 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00003718 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3719 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003720 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00003721 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00003722
Chris Lattner84a03502006-10-27 23:50:33 +00003723 // If this terminator has multiple identical successors (common for
3724 // switches), only handle each succ once.
3725 unsigned SuccMBBNo = SuccMBB->getNumber();
3726 if (SuccsHandled[SuccMBBNo]) continue;
3727 SuccsHandled[SuccMBBNo] = true;
3728
3729 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00003730 PHINode *PN;
3731
3732 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3733 // nodes and Machine PHI nodes, but the incoming operands have not been
3734 // emitted yet.
3735 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00003736 (PN = dyn_cast<PHINode>(I)); ++I) {
3737 // Ignore dead phi's.
3738 if (PN->use_empty()) continue;
3739
3740 unsigned Reg;
3741 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3742 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3743 unsigned &RegOut = ConstantsOut[C];
3744 if (RegOut == 0) {
3745 RegOut = FuncInfo.CreateRegForValue(C);
3746 UnorderedChains.push_back(
3747 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00003748 }
Chris Lattner84a03502006-10-27 23:50:33 +00003749 Reg = RegOut;
3750 } else {
3751 Reg = FuncInfo.ValueMap[PHIOp];
3752 if (Reg == 0) {
3753 assert(isa<AllocaInst>(PHIOp) &&
3754 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3755 "Didn't codegen value into a register!??");
3756 Reg = FuncInfo.CreateRegForValue(PHIOp);
3757 UnorderedChains.push_back(
3758 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00003759 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003760 }
Chris Lattner84a03502006-10-27 23:50:33 +00003761
3762 // Remember that this register needs to added to the machine PHI node as
3763 // the input for this MBB.
3764 MVT::ValueType VT = TLI.getValueType(PN->getType());
3765 unsigned NumElements;
3766 if (VT != MVT::Vector)
3767 NumElements = TLI.getNumElements(VT);
3768 else {
3769 MVT::ValueType VT1,VT2;
3770 NumElements =
3771 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3772 VT1, VT2);
3773 }
3774 for (unsigned i = 0, e = NumElements; i != e; ++i)
3775 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3776 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003777 }
3778 ConstantsOut.clear();
3779
Chris Lattner718b5c22005-01-13 17:59:43 +00003780 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003781 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003782 SDOperand Root = SDL.getRoot();
3783 if (Root.getOpcode() != ISD::EntryToken) {
3784 unsigned i = 0, e = UnorderedChains.size();
3785 for (; i != e; ++i) {
3786 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3787 if (UnorderedChains[i].Val->getOperand(0) == Root)
3788 break; // Don't add the root if we already indirectly depend on it.
3789 }
3790
3791 if (i == e)
3792 UnorderedChains.push_back(Root);
3793 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003794 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3795 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003796 }
3797
Chris Lattner7a60d912005-01-07 07:47:53 +00003798 // Lower the terminator after the copies are emitted.
3799 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003800
Nate Begemaned728c12006-03-27 01:32:24 +00003801 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003802 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003803 SwitchCases.clear();
3804 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003805 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003806
Chris Lattner4108bb02005-01-17 19:43:36 +00003807 // Make sure the root of the DAG is up-to-date.
3808 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003809}
3810
Nate Begemaned728c12006-03-27 01:32:24 +00003811void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003812 // Get alias analysis for load/store combining.
3813 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3814
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003815 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003816 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003817
Chris Lattner7a60d912005-01-07 07:47:53 +00003818 DEBUG(std::cerr << "Lowered selection DAG:\n");
3819 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003820
Chris Lattner7a60d912005-01-07 07:47:53 +00003821 // Second step, hack on the DAG until it only uses operations and types that
3822 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003823 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003824
Chris Lattner7a60d912005-01-07 07:47:53 +00003825 DEBUG(std::cerr << "Legalized selection DAG:\n");
3826 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003827
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003828 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003829 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003830
Evan Cheng739a6a42006-01-21 02:32:06 +00003831 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003832
Chris Lattner5ca31d92005-03-30 01:10:47 +00003833 // Third, instruction select all of the operations to machine code, adding the
3834 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003835 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003836
Chris Lattner7a60d912005-01-07 07:47:53 +00003837 DEBUG(std::cerr << "Selected machine code:\n");
3838 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003839}
Chris Lattner7a60d912005-01-07 07:47:53 +00003840
Nate Begemaned728c12006-03-27 01:32:24 +00003841void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3842 FunctionLoweringInfo &FuncInfo) {
3843 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3844 {
3845 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3846 CurDAG = &DAG;
3847
3848 // First step, lower LLVM code to some DAG. This DAG may use operations and
3849 // types that are not supported by the target.
3850 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3851
3852 // Second step, emit the lowered DAG as machine code.
3853 CodeGenAndEmitDAG(DAG);
3854 }
3855
Chris Lattner5ca31d92005-03-30 01:10:47 +00003856 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003857 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003858 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003859 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3860 MachineInstr *PHI = PHINodesToUpdate[i].first;
3861 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3862 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003863 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003864 PHI->addMachineBasicBlockOperand(BB);
3865 }
3866 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003867 }
Nate Begemaned728c12006-03-27 01:32:24 +00003868
Nate Begeman866b4b42006-04-23 06:26:20 +00003869 // If the JumpTable record is filled in, then we need to emit a jump table.
3870 // Updating the PHI nodes is tricky in this case, since we need to determine
3871 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003872 if (JT.Reg) {
3873 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3874 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3875 CurDAG = &SDAG;
3876 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003877 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003878 // Set the current basic block to the mbb we wish to insert the code into
3879 BB = JT.MBB;
3880 SDL.setCurrentBasicBlock(BB);
3881 // Emit the code
3882 SDL.visitJumpTable(JT);
3883 SDAG.setRoot(SDL.getRoot());
3884 CodeGenAndEmitDAG(SDAG);
3885 // Update PHI Nodes
3886 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3887 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3888 MachineBasicBlock *PHIBB = PHI->getParent();
3889 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3890 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003891 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003892 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003893 PHI->addMachineBasicBlockOperand(RangeBB);
3894 }
3895 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003896 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003897 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003898 }
3899 }
3900 return;
3901 }
3902
Chris Lattner76a7bc82006-10-22 23:00:53 +00003903 // If the switch block involved a branch to one of the actual successors, we
3904 // need to update PHI nodes in that block.
3905 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3906 MachineInstr *PHI = PHINodesToUpdate[i].first;
3907 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3908 "This is not a machine PHI node that we are updating!");
3909 if (BB->isSuccessor(PHI->getParent())) {
3910 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3911 PHI->addMachineBasicBlockOperand(BB);
3912 }
3913 }
3914
Nate Begemaned728c12006-03-27 01:32:24 +00003915 // If we generated any switch lowering information, build and codegen any
3916 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003917 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003918 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3919 CurDAG = &SDAG;
3920 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003921
Nate Begemaned728c12006-03-27 01:32:24 +00003922 // Set the current basic block to the mbb we wish to insert the code into
3923 BB = SwitchCases[i].ThisBB;
3924 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003925
Nate Begemaned728c12006-03-27 01:32:24 +00003926 // Emit the code
3927 SDL.visitSwitchCase(SwitchCases[i]);
3928 SDAG.setRoot(SDL.getRoot());
3929 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003930
3931 // Handle any PHI nodes in successors of this chunk, as if we were coming
3932 // from the original BB before switch expansion. Note that PHI nodes can
3933 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3934 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00003935 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00003936 for (MachineBasicBlock::iterator Phi = BB->begin();
3937 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3938 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3939 for (unsigned pn = 0; ; ++pn) {
3940 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3941 if (PHINodesToUpdate[pn].first == Phi) {
3942 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3943 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3944 break;
3945 }
3946 }
Nate Begemaned728c12006-03-27 01:32:24 +00003947 }
Chris Lattner707339a52006-09-07 01:59:34 +00003948
3949 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00003950 if (BB == SwitchCases[i].FalseBB)
3951 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00003952
3953 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00003954 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00003955 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003956 }
Chris Lattner963ddad2006-10-24 17:57:59 +00003957 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003958 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003959}
Evan Cheng739a6a42006-01-21 02:32:06 +00003960
Jim Laskey95eda5b2006-08-01 14:21:23 +00003961
Evan Cheng739a6a42006-01-21 02:32:06 +00003962//===----------------------------------------------------------------------===//
3963/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3964/// target node in the graph.
3965void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3966 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003967
Jim Laskey29e635d2006-08-02 12:30:23 +00003968 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003969
3970 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003971 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003972 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003973 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003974
Jim Laskey03593f72006-08-01 18:29:48 +00003975 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003976 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003977 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003978}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003979
Chris Lattner47639db2006-03-06 00:22:00 +00003980
Jim Laskey03593f72006-08-01 18:29:48 +00003981HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3982 return new HazardRecognizer();
3983}
3984
Chris Lattner6df34962006-10-11 03:58:02 +00003985//===----------------------------------------------------------------------===//
3986// Helper functions used by the generated instruction selector.
3987//===----------------------------------------------------------------------===//
3988// Calls to these methods are generated by tblgen.
3989
3990/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3991/// the dag combiner simplified the 255, we still want to match. RHS is the
3992/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3993/// specified in the .td file (e.g. 255).
3994bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3995 int64_t DesiredMaskS) {
3996 uint64_t ActualMask = RHS->getValue();
3997 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3998
3999 // If the actual mask exactly matches, success!
4000 if (ActualMask == DesiredMask)
4001 return true;
4002
4003 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4004 if (ActualMask & ~DesiredMask)
4005 return false;
4006
4007 // Otherwise, the DAG Combiner may have proven that the value coming in is
4008 // either already zero or is not demanded. Check for known zero input bits.
4009 uint64_t NeededMask = DesiredMask & ~ActualMask;
4010 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4011 return true;
4012
4013 // TODO: check to see if missing bits are just not demanded.
4014
4015 // Otherwise, this pattern doesn't match.
4016 return false;
4017}
4018
4019/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4020/// the dag combiner simplified the 255, we still want to match. RHS is the
4021/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4022/// specified in the .td file (e.g. 255).
4023bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4024 int64_t DesiredMaskS) {
4025 uint64_t ActualMask = RHS->getValue();
4026 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4027
4028 // If the actual mask exactly matches, success!
4029 if (ActualMask == DesiredMask)
4030 return true;
4031
4032 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4033 if (ActualMask & ~DesiredMask)
4034 return false;
4035
4036 // Otherwise, the DAG Combiner may have proven that the value coming in is
4037 // either already zero or is not demanded. Check for known zero input bits.
4038 uint64_t NeededMask = DesiredMask & ~ActualMask;
4039
4040 uint64_t KnownZero, KnownOne;
4041 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4042
4043 // If all the missing bits in the or are already known to be set, match!
4044 if ((NeededMask & KnownOne) == NeededMask)
4045 return true;
4046
4047 // TODO: check to see if missing bits are just not demanded.
4048
4049 // Otherwise, this pattern doesn't match.
4050 return false;
4051}
4052
Jim Laskey03593f72006-08-01 18:29:48 +00004053
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004054/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4055/// by tblgen. Others should not call it.
4056void SelectionDAGISel::
4057SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4058 std::vector<SDOperand> InOps;
4059 std::swap(InOps, Ops);
4060
4061 Ops.push_back(InOps[0]); // input chain.
4062 Ops.push_back(InOps[1]); // input asm string.
4063
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004064 unsigned i = 2, e = InOps.size();
4065 if (InOps[e-1].getValueType() == MVT::Flag)
4066 --e; // Don't process a flag operand if it is here.
4067
4068 while (i != e) {
4069 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4070 if ((Flags & 7) != 4 /*MEM*/) {
4071 // Just skip over this operand, copying the operands verbatim.
4072 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4073 i += (Flags >> 3) + 1;
4074 } else {
4075 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4076 // Otherwise, this is a memory operand. Ask the target to select it.
4077 std::vector<SDOperand> SelOps;
4078 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4079 std::cerr << "Could not match memory address. Inline asm failure!\n";
4080 exit(1);
4081 }
4082
4083 // Add this to the output node.
4084 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4085 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4086 i += 2;
4087 }
4088 }
4089
4090 // Add the flag input back if present.
4091 if (e != InOps.size())
4092 Ops.push_back(InOps.back());
4093}