blob: 0295fc3b78bb8c1200fca349357324105065d824 [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;
285 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 (PN = dyn_cast<PHINode>(I)); ++I)
287 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000288 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);
297 }
Chris Lattner8ea875f2005-01-07 21:34:19 +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);
500 void ExportFromCurrentBlock(Value *V);
501
Chris Lattner7a60d912005-01-07 07:47:53 +0000502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000505 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507
Nate Begemaned728c12006-03-27 01:32:24 +0000508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000511
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000518 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 else
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000524 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000525 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 else
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000531 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000532 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
533 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
534 void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV, ISD::VSDIV); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000536 const Type *Ty = I.getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000537 if (Ty->isFloatingPoint())
538 visitFPBinary(I, ISD::FREM, 0);
539 else
540 visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000541 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000542 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
543 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
544 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000545 void visitShl(User &I) { visitShift(I, ISD::SHL); }
546 void visitShr(User &I) {
547 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 }
549
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000550 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
551 ISD::CondCode FPOpc);
552 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
553 ISD::SETOEQ); }
554 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
555 ISD::SETUNE); }
556 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
557 ISD::SETOLE); }
558 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
559 ISD::SETOGE); }
560 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
561 ISD::SETOLT); }
562 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
563 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000564
Chris Lattner67271862006-03-29 00:11:43 +0000565 void visitExtractElement(User &I);
566 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000567 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000568
Chris Lattner7a60d912005-01-07 07:47:53 +0000569 void visitGetElementPtr(User &I);
570 void visitCast(User &I);
571 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000572
573 void visitMalloc(MallocInst &I);
574 void visitFree(FreeInst &I);
575 void visitAlloca(AllocaInst &I);
576 void visitLoad(LoadInst &I);
577 void visitStore(StoreInst &I);
578 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
579 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000580 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000581 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000582 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000583
Chris Lattner7a60d912005-01-07 07:47:53 +0000584 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000585 void visitVAArg(VAArgInst &I);
586 void visitVAEnd(CallInst &I);
587 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000588 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000589
Chris Lattner875def92005-01-11 05:56:49 +0000590 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000591
592 void visitUserOp1(Instruction &I) {
593 assert(0 && "UserOp1 should not exist at instruction selection time!");
594 abort();
595 }
596 void visitUserOp2(Instruction &I) {
597 assert(0 && "UserOp2 should not exist at instruction selection time!");
598 abort();
599 }
600};
601} // end namespace llvm
602
Chris Lattner8471b152006-03-16 19:57:50 +0000603SDOperand SelectionDAGLowering::getValue(const Value *V) {
604 SDOperand &N = NodeMap[V];
605 if (N.Val) return N;
606
607 const Type *VTy = V->getType();
608 MVT::ValueType VT = TLI.getValueType(VTy);
609 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
611 visit(CE->getOpcode(), *CE);
612 assert(N.Val && "visit didn't populate the ValueMap!");
613 return N;
614 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
615 return N = DAG.getGlobalAddress(GV, VT);
616 } else if (isa<ConstantPointerNull>(C)) {
617 return N = DAG.getConstant(0, TLI.getPointerTy());
618 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000619 if (!isa<PackedType>(VTy))
620 return N = DAG.getNode(ISD::UNDEF, VT);
621
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000622 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000623 const PackedType *PTy = cast<PackedType>(VTy);
624 unsigned NumElements = PTy->getNumElements();
625 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
626
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000627 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000628 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
629
630 // Create a VConstant node with generic Vector type.
631 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
632 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000633 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
634 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000635 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
636 return N = DAG.getConstantFP(CFP->getValue(), VT);
637 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
638 unsigned NumElements = PTy->getNumElements();
639 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000640
641 // Now that we know the number and type of the elements, push a
642 // Constant or ConstantFP node onto the ops list for each element of
643 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000644 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000645 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000646 for (unsigned i = 0; i != NumElements; ++i)
647 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000648 } else {
649 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
650 SDOperand Op;
651 if (MVT::isFloatingPoint(PVT))
652 Op = DAG.getConstantFP(0, PVT);
653 else
654 Op = DAG.getConstant(0, PVT);
655 Ops.assign(NumElements, Op);
656 }
657
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000658 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000659 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
660 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000661 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000662 } else {
663 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000664 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000665 }
666 }
667
668 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
669 std::map<const AllocaInst*, int>::iterator SI =
670 FuncInfo.StaticAllocaMap.find(AI);
671 if (SI != FuncInfo.StaticAllocaMap.end())
672 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
673 }
674
675 std::map<const Value*, unsigned>::const_iterator VMI =
676 FuncInfo.ValueMap.find(V);
677 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
678
679 unsigned InReg = VMI->second;
680
681 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000682 if (VT != MVT::Vector) {
683 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000684
Chris Lattner5fe1f542006-03-31 02:06:56 +0000685 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
686 if (DestVT < VT) {
687 // Source must be expanded. This input value is actually coming from the
688 // register pair VMI->second and VMI->second+1.
689 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
690 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
691 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000692 if (MVT::isFloatingPoint(VT))
693 N = DAG.getNode(ISD::FP_ROUND, VT, N);
694 else
695 N = DAG.getNode(ISD::TRUNCATE, VT, N);
696 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000697 } else {
698 // Otherwise, if this is a vector, make it available as a generic vector
699 // here.
700 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000701 const PackedType *PTy = cast<PackedType>(VTy);
702 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000703 PTyLegalElementVT);
704
705 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000706 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000707 if (PTyElementVT == PTyLegalElementVT) {
708 // If the value types are legal, just VBUILD the CopyFromReg nodes.
709 for (unsigned i = 0; i != NE; ++i)
710 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 PTyElementVT));
712 } else if (PTyElementVT < PTyLegalElementVT) {
713 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
714 for (unsigned i = 0; i != NE; ++i) {
715 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
716 PTyElementVT);
717 if (MVT::isFloatingPoint(PTyElementVT))
718 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
719 else
720 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
721 Ops.push_back(Op);
722 }
723 } else {
724 // If the register was expanded, use BUILD_PAIR.
725 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
726 for (unsigned i = 0; i != NE/2; ++i) {
727 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 PTyElementVT);
729 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
730 PTyElementVT);
731 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
732 }
733 }
734
735 Ops.push_back(DAG.getConstant(NE, MVT::i32));
736 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000737 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000738
739 // Finally, use a VBIT_CONVERT to make this available as the appropriate
740 // vector type.
741 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
742 DAG.getConstant(PTy->getNumElements(),
743 MVT::i32),
744 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000745 }
746
747 return N;
748}
749
750
Chris Lattner7a60d912005-01-07 07:47:53 +0000751void SelectionDAGLowering::visitRet(ReturnInst &I) {
752 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000753 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000754 return;
755 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000756 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000757 NewValues.push_back(getRoot());
758 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
759 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000760 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000761
762 // If this is an integer return value, we need to promote it ourselves to
763 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
764 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000765 // FIXME: C calling convention requires the return type to be promoted to
766 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000767 if (MVT::isInteger(RetOp.getValueType()) &&
768 RetOp.getValueType() < MVT::i64) {
769 MVT::ValueType TmpVT;
770 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
771 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
772 else
773 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000774
Evan Chenga2e99532006-05-26 23:09:09 +0000775 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000776 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
777 else
778 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
779 }
780 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000781 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000783 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
784 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000785}
786
Chris Lattnered0110b2006-10-27 21:36:01 +0000787/// ExportFromCurrentBlock - If this condition isn't known to be exported from
788/// the current basic block, add it to ValueMap now so that we'll get a
789/// CopyTo/FromReg.
790void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
791 // No need to export constants.
792 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
793
794 // Already exported?
795 if (FuncInfo.isExportedInst(V)) return;
796
797 unsigned Reg = FuncInfo.InitializeRegForValue(V);
798 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
799}
800
801/// FindMergedConditions - If Cond is an expression like
802void SelectionDAGLowering::FindMergedConditions(Value *Cond,
803 MachineBasicBlock *TBB,
804 MachineBasicBlock *FBB,
805 MachineBasicBlock *CurBB,
806 unsigned Opc) {
807 // FIXME: HANDLE AND.
808 // FIXME: HANDLE NOT
809
810 // If this node is not part of the or/and tree, emit it as a branch.
811 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
812
813 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
814 BOp->getParent() != CurBB->getBasicBlock()) {
815 const BasicBlock *BB = CurBB->getBasicBlock();
816
817 // If the leaf of the tree is a setcond inst, merge the condition into the
818 // caseblock.
819 if (BOp && isa<SetCondInst>(BOp) &&
820 // The operands of the setcc have to be in this block. We don't know
821 // how to export them from some other block.
822 (!isa<Instruction>(BOp->getOperand(0)) ||
823 cast<Instruction>(BOp->getOperand(0))->getParent() == BB ||
824 FuncInfo.isExportedInst(BOp->getOperand(0))) &&
825 (!isa<Instruction>(BOp->getOperand(1)) ||
826 cast<Instruction>(BOp->getOperand(1))->getParent() == BB ||
827 FuncInfo.isExportedInst(BOp->getOperand(1)))) {
828 ExportFromCurrentBlock(BOp->getOperand(0));
829 ExportFromCurrentBlock(BOp->getOperand(1));
830
831 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
832 switch (BOp->getOpcode()) {
833 default: assert(0 && "Unknown setcc opcode!");
834 case Instruction::SetEQ:
835 SignCond = ISD::SETEQ;
836 UnsCond = ISD::SETEQ;
837 FPCond = ISD::SETOEQ;
838 break;
839 case Instruction::SetNE:
840 SignCond = ISD::SETNE;
841 UnsCond = ISD::SETNE;
842 FPCond = ISD::SETUNE;
843 break;
844 case Instruction::SetLE:
845 SignCond = ISD::SETLE;
846 UnsCond = ISD::SETULE;
847 FPCond = ISD::SETOLE;
848 break;
849 case Instruction::SetGE:
850 SignCond = ISD::SETGE;
851 UnsCond = ISD::SETUGE;
852 FPCond = ISD::SETOGE;
853 break;
854 case Instruction::SetLT:
855 SignCond = ISD::SETLT;
856 UnsCond = ISD::SETULT;
857 FPCond = ISD::SETOLT;
858 break;
859 case Instruction::SetGT:
860 SignCond = ISD::SETGT;
861 UnsCond = ISD::SETUGT;
862 FPCond = ISD::SETOGT;
863 break;
864 }
865
866 const Type *OpType = BOp->getOperand(0)->getType();
867 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
868 OpType = PTy->getElementType();
869
870 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
871 Condition = FPCond;
872 else if (OpType->isUnsigned())
873 Condition = UnsCond;
874 else
875 Condition = SignCond;
876
877 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
878 BOp->getOperand(1), TBB, FBB, CurBB);
879 SwitchCases.push_back(CB);
880 return;
881 }
882
883 // Create a CaseBlock record representing this branch.
884 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
885 TBB, FBB, CurBB);
886 SwitchCases.push_back(CB);
887 ExportFromCurrentBlock(Cond);
888 return;
889 }
890
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000891
892 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000893 MachineFunction::iterator BBI = CurBB;
894 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
895 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
896
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000897 if (Opc == Instruction::Or) {
898 // Codegen X | Y as:
899 // jmp_if_X TBB
900 // jmp TmpBB
901 // TmpBB:
902 // jmp_if_Y TBB
903 // jmp FBB
904 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000905
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000906 // Emit the LHS condition.
907 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
908
909 // Emit the RHS condition into TmpBB.
910 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
911 } else {
912 assert(Opc == Instruction::And && "Unknown merge op!");
913 // Codegen X & Y as:
914 // jmp_if_X TmpBB
915 // jmp FBB
916 // TmpBB:
917 // jmp_if_Y TBB
918 // jmp FBB
919 //
920 // This requires creation of TmpBB after CurBB.
921
922 // Emit the LHS condition.
923 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
924
925 // Emit the RHS condition into TmpBB.
926 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
927 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000928}
929
Chris Lattner7a60d912005-01-07 07:47:53 +0000930void SelectionDAGLowering::visitBr(BranchInst &I) {
931 // Update machine-CFG edges.
932 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000933
934 // Figure out which block is immediately after the current one.
935 MachineBasicBlock *NextBlock = 0;
936 MachineFunction::iterator BBI = CurMBB;
937 if (++BBI != CurMBB->getParent()->end())
938 NextBlock = BBI;
939
940 if (I.isUnconditional()) {
941 // If this is not a fall-through branch, emit the branch.
942 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000943 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000944 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000945
Chris Lattner963ddad2006-10-24 17:57:59 +0000946 // Update machine-CFG edges.
947 CurMBB->addSuccessor(Succ0MBB);
948
949 return;
950 }
951
952 // If this condition is one of the special cases we handle, do special stuff
953 // now.
954 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000955 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000956
957 // If this is a series of conditions that are or'd or and'd together, emit
958 // this as a sequence of branches instead of setcc's with and/or operations.
959 // For example, instead of something like:
960 // cmp A, B
961 // C = seteq
962 // cmp D, E
963 // F = setle
964 // or C, F
965 // jnz foo
966 // Emit:
967 // cmp A, B
968 // je foo
969 // cmp D, E
970 // jle foo
971 //
972 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
973 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000974 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000975 BOp->getOpcode() == Instruction::Or)) {
976 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnered0110b2006-10-27 21:36:01 +0000977 visitSwitchCase(SwitchCases[0]);
978 SwitchCases.erase(SwitchCases.begin());
979 return;
980 }
981 }
Chris Lattner61bcf912006-10-24 18:07:37 +0000982
983 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +0000984 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +0000985 Succ0MBB, Succ1MBB, CurMBB);
986 // Use visitSwitchCase to actually insert the fast branch sequence for this
987 // cond branch.
988 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000989}
990
Nate Begemaned728c12006-03-27 01:32:24 +0000991/// visitSwitchCase - Emits the necessary code to represent a single node in
992/// the binary search tree resulting from lowering a switch instruction.
993void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +0000994 SDOperand Cond;
995 SDOperand CondLHS = getValue(CB.CmpLHS);
996
Chris Lattnered0110b2006-10-27 21:36:01 +0000997 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
998 // handle common cases produced by branch lowering.
999 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001000 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001001 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1002 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1003 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1004 } else
1005 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001006
1007 // Set NextBlock to be the MBB immediately after the current one, if any.
1008 // This is used to avoid emitting unnecessary branches to the next block.
1009 MachineBasicBlock *NextBlock = 0;
1010 MachineFunction::iterator BBI = CurMBB;
1011 if (++BBI != CurMBB->getParent()->end())
1012 NextBlock = BBI;
1013
1014 // If the lhs block is the next block, invert the condition so that we can
1015 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001016 if (CB.TrueBB == NextBlock) {
1017 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001018 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1019 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1020 }
1021 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001022 DAG.getBasicBlock(CB.TrueBB));
1023 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001024 DAG.setRoot(BrCond);
1025 else
1026 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001027 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001028 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001029 CurMBB->addSuccessor(CB.TrueBB);
1030 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001031}
1032
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001033void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001034 // Emit the code for the jump table
1035 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001036 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
1037 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +00001038 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001039 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +00001040 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001041 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1042 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001043 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +00001044 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
1045 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +00001046 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001047 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +00001048 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +00001049 // For Pic, the sequence is:
1050 // BRIND(load(Jumptable + index) + RelocBase)
1051 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +00001052 SDOperand Reloc;
1053 if (TLI.usesGlobalOffsetTable())
1054 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1055 else
1056 Reloc = TAB;
Chris Lattner4c3ef472006-10-22 22:47:10 +00001057 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1058 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman78756502006-07-27 01:13:04 +00001059 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
1060 } else {
1061 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
1062 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001063}
1064
Nate Begemaned728c12006-03-27 01:32:24 +00001065void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1066 // Figure out which block is immediately after the current one.
1067 MachineBasicBlock *NextBlock = 0;
1068 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001069
Nate Begemaned728c12006-03-27 01:32:24 +00001070 if (++BBI != CurMBB->getParent()->end())
1071 NextBlock = BBI;
1072
Chris Lattner6d6fc262006-10-22 21:36:53 +00001073 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1074
Nate Begemaned728c12006-03-27 01:32:24 +00001075 // If there is only the default destination, branch to it if it is not the
1076 // next basic block. Otherwise, just fall through.
1077 if (I.getNumOperands() == 2) {
1078 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001079
Nate Begemaned728c12006-03-27 01:32:24 +00001080 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001081 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001082 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001083 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001084
Chris Lattner6d6fc262006-10-22 21:36:53 +00001085 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001086 return;
1087 }
1088
1089 // If there are any non-default case statements, create a vector of Cases
1090 // representing each one, and sort the vector so that we can efficiently
1091 // create a binary search tree from them.
1092 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001093
Nate Begemaned728c12006-03-27 01:32:24 +00001094 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1095 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1096 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1097 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001098
Nate Begemaned728c12006-03-27 01:32:24 +00001099 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1100
1101 // Get the Value to be switched on and default basic blocks, which will be
1102 // inserted into CaseBlock records, representing basic blocks in the binary
1103 // search tree.
1104 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001105
1106 // Get the MachineFunction which holds the current MBB. This is used during
1107 // emission of jump tables, and when inserting any additional MBBs necessary
1108 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001109 MachineFunction *CurMF = CurMBB->getParent();
1110 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001111
1112 // If the switch has few cases (two or less) emit a series of specific
1113 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001114 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001115 // TODO: If any two of the cases has the same destination, and if one value
1116 // is the same as the other, but has one bit unset that the other has set,
1117 // use bit manipulation to do two compares at once. For example:
1118 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1119
Chris Lattner4c931502006-10-23 18:38:22 +00001120 // Rearrange the case blocks so that the last one falls through if possible.
1121 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1122 // The last case block won't fall through into 'NextBlock' if we emit the
1123 // branches in this order. See if rearranging a case value would help.
1124 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1125 if (Cases[i].second == NextBlock) {
1126 std::swap(Cases[i], Cases.back());
1127 break;
1128 }
1129 }
1130 }
1131
Chris Lattner6d6fc262006-10-22 21:36:53 +00001132 // Create a CaseBlock record representing a conditional branch to
1133 // the Case's target mbb if the value being switched on SV is equal
1134 // to C.
1135 MachineBasicBlock *CurBlock = CurMBB;
1136 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1137 MachineBasicBlock *FallThrough;
1138 if (i != e-1) {
1139 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1140 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1141 } else {
1142 // If the last case doesn't match, go to the default block.
1143 FallThrough = Default;
1144 }
1145
1146 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1147 Cases[i].second, FallThrough, CurBlock);
1148
1149 // If emitting the first comparison, just call visitSwitchCase to emit the
1150 // code into the current block. Otherwise, push the CaseBlock onto the
1151 // vector to be later processed by SDISel, and insert the node's MBB
1152 // before the next MBB.
1153 if (CurBlock == CurMBB)
1154 visitSwitchCase(CB);
1155 else
1156 SwitchCases.push_back(CB);
1157
1158 CurBlock = FallThrough;
1159 }
1160 return;
1161 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001162
Nate Begemand7a19102006-05-08 16:51:36 +00001163 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1164 // target supports indirect branches, then emit a jump table rather than
1165 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +00001166 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +00001167 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001168 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1169 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001170 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1171
Nate Begemand7a19102006-05-08 16:51:36 +00001172 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001173 // Create a new basic block to hold the code for loading the address
1174 // of the jump table, and jumping to it. Update successor information;
1175 // we will either branch to the default case for the switch, or the jump
1176 // table.
1177 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1178 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1179 CurMBB->addSuccessor(Default);
1180 CurMBB->addSuccessor(JumpTableBB);
1181
1182 // Subtract the lowest switch case value from the value being switched on
1183 // and conditional branch to default mbb if the result is greater than the
1184 // difference between smallest and largest cases.
1185 SDOperand SwitchOp = getValue(SV);
1186 MVT::ValueType VT = SwitchOp.getValueType();
1187 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1188 DAG.getConstant(First, VT));
1189
1190 // The SDNode we just created, which holds the value being switched on
1191 // minus the the smallest case value, needs to be copied to a virtual
1192 // register so it can be used as an index into the jump table in a
1193 // subsequent basic block. This value may be smaller or larger than the
1194 // target's pointer type, and therefore require extension or truncating.
1195 if (VT > TLI.getPointerTy())
1196 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1197 else
1198 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001199
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001200 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1201 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1202
1203 // Emit the range check for the jump table, and branch to the default
1204 // block for the switch statement if the value being switched on exceeds
1205 // the largest case in the switch.
1206 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1207 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1208 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1209 DAG.getBasicBlock(Default)));
1210
Nate Begemandf488392006-05-03 03:48:02 +00001211 // Build a vector of destination BBs, corresponding to each target
1212 // of the jump table. If the value of the jump table slot corresponds to
1213 // a case statement, push the case's BB onto the vector, otherwise, push
1214 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001215 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001216 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001217 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001218 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001219 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001220 ++ii;
1221 } else {
1222 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001223 }
Nate Begemandf488392006-05-03 03:48:02 +00001224
1225 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001226 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1227 E = DestBBs.end(); I != E; ++I)
1228 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +00001229
1230 // Create a jump table index for this jump table, or return an existing
1231 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001232 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1233
1234 // Set the jump table information so that we can codegen it as a second
1235 // MachineBasicBlock
1236 JT.Reg = JumpTableReg;
1237 JT.JTI = JTI;
1238 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001239 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001240 return;
1241 }
1242 }
Nate Begemaned728c12006-03-27 01:32:24 +00001243
1244 // Push the initial CaseRec onto the worklist
1245 std::vector<CaseRec> CaseVec;
1246 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1247
1248 while (!CaseVec.empty()) {
1249 // Grab a record representing a case range to process off the worklist
1250 CaseRec CR = CaseVec.back();
1251 CaseVec.pop_back();
1252
1253 // Size is the number of Cases represented by this range. If Size is 1,
1254 // then we are processing a leaf of the binary search tree. Otherwise,
1255 // we need to pick a pivot, and push left and right ranges onto the
1256 // worklist.
1257 unsigned Size = CR.Range.second - CR.Range.first;
1258
1259 if (Size == 1) {
1260 // Create a CaseBlock record representing a conditional branch to
1261 // the Case's target mbb if the value being switched on SV is equal
1262 // to C. Otherwise, branch to default.
1263 Constant *C = CR.Range.first->first;
1264 MachineBasicBlock *Target = CR.Range.first->second;
1265 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1266 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001267
Nate Begemaned728c12006-03-27 01:32:24 +00001268 // If the MBB representing the leaf node is the current MBB, then just
1269 // call visitSwitchCase to emit the code into the current block.
1270 // Otherwise, push the CaseBlock onto the vector to be later processed
1271 // by SDISel, and insert the node's MBB before the next MBB.
1272 if (CR.CaseBB == CurMBB)
1273 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001274 else
Nate Begemaned728c12006-03-27 01:32:24 +00001275 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001276 } else {
1277 // split case range at pivot
1278 CaseItr Pivot = CR.Range.first + (Size / 2);
1279 CaseRange LHSR(CR.Range.first, Pivot);
1280 CaseRange RHSR(Pivot, CR.Range.second);
1281 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001282 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001283
Nate Begemaned728c12006-03-27 01:32:24 +00001284 // We know that we branch to the LHS if the Value being switched on is
1285 // less than the Pivot value, C. We use this to optimize our binary
1286 // tree a bit, by recognizing that if SV is greater than or equal to the
1287 // LHS's Case Value, and that Case Value is exactly one less than the
1288 // Pivot's Value, then we can branch directly to the LHS's Target,
1289 // rather than creating a leaf node for it.
1290 if ((LHSR.second - LHSR.first) == 1 &&
1291 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001292 cast<ConstantIntegral>(C)->getZExtValue() ==
1293 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001294 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001295 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001296 TrueBB = new MachineBasicBlock(LLVMBB);
1297 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1298 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001299 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001300
Nate Begemaned728c12006-03-27 01:32:24 +00001301 // Similar to the optimization above, if the Value being switched on is
1302 // known to be less than the Constant CR.LT, and the current Case Value
1303 // is CR.LT - 1, then we can branch directly to the target block for
1304 // the current Case Value, rather than emitting a RHS leaf node for it.
1305 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001306 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1307 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001308 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001309 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001310 FalseBB = new MachineBasicBlock(LLVMBB);
1311 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1312 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001313 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001314
Nate Begemaned728c12006-03-27 01:32:24 +00001315 // Create a CaseBlock record representing a conditional branch to
1316 // the LHS node if the value being switched on SV is less than C.
1317 // Otherwise, branch to LHS.
1318 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001319 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001320
Nate Begemaned728c12006-03-27 01:32:24 +00001321 if (CR.CaseBB == CurMBB)
1322 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001323 else
Nate Begemaned728c12006-03-27 01:32:24 +00001324 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001325 }
1326 }
1327}
1328
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001329void SelectionDAGLowering::visitSub(User &I) {
1330 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001331 if (I.getType()->isFloatingPoint()) {
1332 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1333 if (CFP->isExactlyValue(-0.0)) {
1334 SDOperand Op2 = getValue(I.getOperand(1));
1335 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1336 return;
1337 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001338 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1339 } else
1340 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001341}
1342
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001343void
1344SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001345 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001346 SDOperand Op1 = getValue(I.getOperand(0));
1347 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001348
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001349 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001350 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1351 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1352 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001353 } else {
1354 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1355 }
1356}
1357
1358void
1359SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1360 const Type *Ty = I.getType();
1361 SDOperand Op1 = getValue(I.getOperand(0));
1362 SDOperand Op2 = getValue(I.getOperand(1));
1363
1364 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1365 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1366 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1367 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1368 } else {
1369 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001370 }
Nate Begeman127321b2005-11-18 07:42:56 +00001371}
Chris Lattner96c26752005-01-19 22:31:21 +00001372
Nate Begeman127321b2005-11-18 07:42:56 +00001373void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1374 SDOperand Op1 = getValue(I.getOperand(0));
1375 SDOperand Op2 = getValue(I.getOperand(1));
1376
1377 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1378
Chris Lattner7a60d912005-01-07 07:47:53 +00001379 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1380}
1381
1382void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001383 ISD::CondCode UnsignedOpcode,
1384 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001385 SDOperand Op1 = getValue(I.getOperand(0));
1386 SDOperand Op2 = getValue(I.getOperand(1));
1387 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001388 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001389 Opcode = FPOpcode;
1390 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001391 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001392 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001393}
1394
1395void SelectionDAGLowering::visitSelect(User &I) {
1396 SDOperand Cond = getValue(I.getOperand(0));
1397 SDOperand TrueVal = getValue(I.getOperand(1));
1398 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001399 if (!isa<PackedType>(I.getType())) {
1400 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1401 TrueVal, FalseVal));
1402 } else {
1403 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1404 *(TrueVal.Val->op_end()-2),
1405 *(TrueVal.Val->op_end()-1)));
1406 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001407}
1408
1409void SelectionDAGLowering::visitCast(User &I) {
1410 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001411 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001412 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001413
Chris Lattner2f4119a2006-03-22 20:09:35 +00001414 if (DestVT == MVT::Vector) {
1415 // This is a cast to a vector from something else. This is always a bit
1416 // convert. Get information about the input vector.
1417 const PackedType *DestTy = cast<PackedType>(I.getType());
1418 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1419 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1420 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1421 DAG.getValueType(EltVT)));
1422 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001423 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001424 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001425 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001426 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001427 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001428 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001429 } else if (isInteger(SrcVT)) {
1430 if (isInteger(DestVT)) { // Int -> Int cast
1431 if (DestVT < SrcVT) // Truncating cast?
1432 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001433 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001434 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001435 else
Chris Lattner4024c002006-03-15 22:19:46 +00001436 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001437 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001438 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001439 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001440 else
Chris Lattner4024c002006-03-15 22:19:46 +00001441 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001442 } else {
1443 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001444 }
Chris Lattner4024c002006-03-15 22:19:46 +00001445 } else if (isFloatingPoint(SrcVT)) {
1446 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1447 if (DestVT < SrcVT) // Rounding cast?
1448 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001449 else
Chris Lattner4024c002006-03-15 22:19:46 +00001450 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001451 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001452 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001453 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001454 else
Chris Lattner4024c002006-03-15 22:19:46 +00001455 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001456 } else {
1457 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001458 }
1459 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001460 assert(SrcVT == MVT::Vector && "Unknown cast!");
1461 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1462 // This is a cast from a vector to something else. This is always a bit
1463 // convert. Get information about the input vector.
1464 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001465 }
1466}
1467
Chris Lattner67271862006-03-29 00:11:43 +00001468void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001469 SDOperand InVec = getValue(I.getOperand(0));
1470 SDOperand InVal = getValue(I.getOperand(1));
1471 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1472 getValue(I.getOperand(2)));
1473
Chris Lattner29b23012006-03-19 01:17:20 +00001474 SDOperand Num = *(InVec.Val->op_end()-2);
1475 SDOperand Typ = *(InVec.Val->op_end()-1);
1476 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1477 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001478}
1479
Chris Lattner67271862006-03-29 00:11:43 +00001480void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001481 SDOperand InVec = getValue(I.getOperand(0));
1482 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1483 getValue(I.getOperand(1)));
1484 SDOperand Typ = *(InVec.Val->op_end()-1);
1485 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1486 TLI.getValueType(I.getType()), InVec, InIdx));
1487}
Chris Lattner32206f52006-03-18 01:44:44 +00001488
Chris Lattner098c01e2006-04-08 04:15:24 +00001489void SelectionDAGLowering::visitShuffleVector(User &I) {
1490 SDOperand V1 = getValue(I.getOperand(0));
1491 SDOperand V2 = getValue(I.getOperand(1));
1492 SDOperand Mask = getValue(I.getOperand(2));
1493
1494 SDOperand Num = *(V1.Val->op_end()-2);
1495 SDOperand Typ = *(V2.Val->op_end()-1);
1496 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1497 V1, V2, Mask, Num, Typ));
1498}
1499
1500
Chris Lattner7a60d912005-01-07 07:47:53 +00001501void SelectionDAGLowering::visitGetElementPtr(User &I) {
1502 SDOperand N = getValue(I.getOperand(0));
1503 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001504
1505 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1506 OI != E; ++OI) {
1507 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001508 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001509 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001510 if (Field) {
1511 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001512 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001513 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001514 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001515 }
1516 Ty = StTy->getElementType(Field);
1517 } else {
1518 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001519
Chris Lattner43535a12005-11-09 04:45:33 +00001520 // If this is a constant subscript, handle it quickly.
1521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001522 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001523 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001524 if (CI->getType()->isSigned())
1525 Offs = (int64_t)
1526 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001527 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001528 Offs =
1529 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001530 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1531 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001532 }
Chris Lattner43535a12005-11-09 04:45:33 +00001533
1534 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001535 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001536 SDOperand IdxN = getValue(Idx);
1537
1538 // If the index is smaller or larger than intptr_t, truncate or extend
1539 // it.
1540 if (IdxN.getValueType() < N.getValueType()) {
1541 if (Idx->getType()->isSigned())
1542 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1543 else
1544 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1545 } else if (IdxN.getValueType() > N.getValueType())
1546 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1547
1548 // If this is a multiply by a power of two, turn it into a shl
1549 // immediately. This is a very common case.
1550 if (isPowerOf2_64(ElementSize)) {
1551 unsigned Amt = Log2_64(ElementSize);
1552 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001553 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001554 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1555 continue;
1556 }
1557
1558 SDOperand Scale = getIntPtrConstant(ElementSize);
1559 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1560 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001561 }
1562 }
1563 setValue(&I, N);
1564}
1565
1566void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1567 // If this is a fixed sized alloca in the entry block of the function,
1568 // allocate it statically on the stack.
1569 if (FuncInfo.StaticAllocaMap.count(&I))
1570 return; // getValue will auto-populate this.
1571
1572 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001573 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1574 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001575 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001576
1577 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001578 MVT::ValueType IntPtr = TLI.getPointerTy();
1579 if (IntPtr < AllocSize.getValueType())
1580 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1581 else if (IntPtr > AllocSize.getValueType())
1582 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001583
Chris Lattnereccb73d2005-01-22 23:04:37 +00001584 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001585 getIntPtrConstant(TySize));
1586
1587 // Handle alignment. If the requested alignment is less than or equal to the
1588 // stack alignment, ignore it and round the size of the allocation up to the
1589 // stack alignment size. If the size is greater than the stack alignment, we
1590 // note this in the DYNAMIC_STACKALLOC node.
1591 unsigned StackAlign =
1592 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1593 if (Align <= StackAlign) {
1594 Align = 0;
1595 // Add SA-1 to the size.
1596 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1597 getIntPtrConstant(StackAlign-1));
1598 // Mask out the low bits for alignment purposes.
1599 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1600 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1601 }
1602
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001603 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001604 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1605 MVT::Other);
1606 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001607 DAG.setRoot(setValue(&I, DSA).getValue(1));
1608
1609 // Inform the Frame Information that we have just allocated a variable-sized
1610 // object.
1611 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1612}
1613
Chris Lattner7a60d912005-01-07 07:47:53 +00001614void SelectionDAGLowering::visitLoad(LoadInst &I) {
1615 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001616
Chris Lattner4d9651c2005-01-17 22:19:26 +00001617 SDOperand Root;
1618 if (I.isVolatile())
1619 Root = getRoot();
1620 else {
1621 // Do not serialize non-volatile loads against each other.
1622 Root = DAG.getRoot();
1623 }
Chris Lattner4024c002006-03-15 22:19:46 +00001624
Evan Chenge71fe34d2006-10-09 20:57:25 +00001625 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001626 Root, I.isVolatile()));
1627}
1628
1629SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001630 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001631 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001632 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001633 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001634 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001635 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1636 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001637 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001638 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001639 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001640
Chris Lattner4024c002006-03-15 22:19:46 +00001641 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001642 DAG.setRoot(L.getValue(1));
1643 else
1644 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001645
1646 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001647}
1648
1649
1650void SelectionDAGLowering::visitStore(StoreInst &I) {
1651 Value *SrcV = I.getOperand(0);
1652 SDOperand Src = getValue(SrcV);
1653 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001654 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1655 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001656}
1657
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001658/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1659/// access memory and has no other side effects at all.
1660static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1661#define GET_NO_MEMORY_INTRINSICS
1662#include "llvm/Intrinsics.gen"
1663#undef GET_NO_MEMORY_INTRINSICS
1664 return false;
1665}
1666
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001667// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1668// have any side-effects or if it only reads memory.
1669static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1670#define GET_SIDE_EFFECT_INFO
1671#include "llvm/Intrinsics.gen"
1672#undef GET_SIDE_EFFECT_INFO
1673 return false;
1674}
1675
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001676/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1677/// node.
1678void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1679 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001680 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001681 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001682
1683 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001684 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001685 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1686 if (OnlyLoad) {
1687 // We don't need to serialize loads against other loads.
1688 Ops.push_back(DAG.getRoot());
1689 } else {
1690 Ops.push_back(getRoot());
1691 }
1692 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001693
1694 // Add the intrinsic ID as an integer operand.
1695 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1696
1697 // Add all operands of the call to the operand list.
1698 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1699 SDOperand Op = getValue(I.getOperand(i));
1700
1701 // If this is a vector type, force it to the right packed type.
1702 if (Op.getValueType() == MVT::Vector) {
1703 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1704 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1705
1706 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1707 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1708 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1709 }
1710
1711 assert(TLI.isTypeLegal(Op.getValueType()) &&
1712 "Intrinsic uses a non-legal type?");
1713 Ops.push_back(Op);
1714 }
1715
1716 std::vector<MVT::ValueType> VTs;
1717 if (I.getType() != Type::VoidTy) {
1718 MVT::ValueType VT = TLI.getValueType(I.getType());
1719 if (VT == MVT::Vector) {
1720 const PackedType *DestTy = cast<PackedType>(I.getType());
1721 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1722
1723 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1724 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1725 }
1726
1727 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1728 VTs.push_back(VT);
1729 }
1730 if (HasChain)
1731 VTs.push_back(MVT::Other);
1732
Chris Lattnerbd887772006-08-14 23:53:35 +00001733 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1734
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001735 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001736 SDOperand Result;
1737 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001738 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1739 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001740 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001741 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1742 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001743 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001744 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1745 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001746
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001747 if (HasChain) {
1748 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1749 if (OnlyLoad)
1750 PendingLoads.push_back(Chain);
1751 else
1752 DAG.setRoot(Chain);
1753 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001754 if (I.getType() != Type::VoidTy) {
1755 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1756 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1757 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1758 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1759 DAG.getValueType(EVT));
1760 }
1761 setValue(&I, Result);
1762 }
1763}
1764
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001765/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1766/// we want to emit this as a call to a named external function, return the name
1767/// otherwise lower it and return null.
1768const char *
1769SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1770 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001771 default:
1772 // By default, turn this into a target intrinsic node.
1773 visitTargetIntrinsic(I, Intrinsic);
1774 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001775 case Intrinsic::vastart: visitVAStart(I); return 0;
1776 case Intrinsic::vaend: visitVAEnd(I); return 0;
1777 case Intrinsic::vacopy: visitVACopy(I); return 0;
1778 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1779 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1780 case Intrinsic::setjmp:
1781 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1782 break;
1783 case Intrinsic::longjmp:
1784 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1785 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001786 case Intrinsic::memcpy_i32:
1787 case Intrinsic::memcpy_i64:
1788 visitMemIntrinsic(I, ISD::MEMCPY);
1789 return 0;
1790 case Intrinsic::memset_i32:
1791 case Intrinsic::memset_i64:
1792 visitMemIntrinsic(I, ISD::MEMSET);
1793 return 0;
1794 case Intrinsic::memmove_i32:
1795 case Intrinsic::memmove_i64:
1796 visitMemIntrinsic(I, ISD::MEMMOVE);
1797 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001798
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001799 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001800 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001801 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001802 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001803 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001804
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001805 Ops[0] = getRoot();
1806 Ops[1] = getValue(SPI.getLineValue());
1807 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001808
Jim Laskeya8bdac82006-03-23 18:06:46 +00001809 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001810 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001811 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1812
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001813 Ops[3] = DAG.getString(CompileUnit->getFileName());
1814 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001815
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001816 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001817 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001818
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001819 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001820 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001821 case Intrinsic::dbg_region_start: {
1822 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1823 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001824 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001825 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001826 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1827 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001828 }
1829
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001830 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001831 }
1832 case Intrinsic::dbg_region_end: {
1833 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1834 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001835 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001836 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001837 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1838 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001839 }
1840
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001841 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001842 }
1843 case Intrinsic::dbg_func_start: {
1844 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1845 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001846 if (DebugInfo && FSI.getSubprogram() &&
1847 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001848 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001849 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1850 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001851 }
1852
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001853 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001854 }
1855 case Intrinsic::dbg_declare: {
1856 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1857 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001858 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001859 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001860 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001861 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001862 }
1863
1864 return 0;
1865 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001866
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001867 case Intrinsic::isunordered_f32:
1868 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001869 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1870 getValue(I.getOperand(2)), ISD::SETUO));
1871 return 0;
1872
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001873 case Intrinsic::sqrt_f32:
1874 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001875 setValue(&I, DAG.getNode(ISD::FSQRT,
1876 getValue(I.getOperand(1)).getValueType(),
1877 getValue(I.getOperand(1))));
1878 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001879 case Intrinsic::powi_f32:
1880 case Intrinsic::powi_f64:
1881 setValue(&I, DAG.getNode(ISD::FPOWI,
1882 getValue(I.getOperand(1)).getValueType(),
1883 getValue(I.getOperand(1)),
1884 getValue(I.getOperand(2))));
1885 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001886 case Intrinsic::pcmarker: {
1887 SDOperand Tmp = getValue(I.getOperand(1));
1888 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1889 return 0;
1890 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001891 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001892 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001893 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1894 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1895 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001896 setValue(&I, Tmp);
1897 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001898 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001899 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001900 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001901 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001902 case Intrinsic::bswap_i64:
1903 setValue(&I, DAG.getNode(ISD::BSWAP,
1904 getValue(I.getOperand(1)).getValueType(),
1905 getValue(I.getOperand(1))));
1906 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001907 case Intrinsic::cttz_i8:
1908 case Intrinsic::cttz_i16:
1909 case Intrinsic::cttz_i32:
1910 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001911 setValue(&I, DAG.getNode(ISD::CTTZ,
1912 getValue(I.getOperand(1)).getValueType(),
1913 getValue(I.getOperand(1))));
1914 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001915 case Intrinsic::ctlz_i8:
1916 case Intrinsic::ctlz_i16:
1917 case Intrinsic::ctlz_i32:
1918 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001919 setValue(&I, DAG.getNode(ISD::CTLZ,
1920 getValue(I.getOperand(1)).getValueType(),
1921 getValue(I.getOperand(1))));
1922 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001923 case Intrinsic::ctpop_i8:
1924 case Intrinsic::ctpop_i16:
1925 case Intrinsic::ctpop_i32:
1926 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001927 setValue(&I, DAG.getNode(ISD::CTPOP,
1928 getValue(I.getOperand(1)).getValueType(),
1929 getValue(I.getOperand(1))));
1930 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001931 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001932 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001933 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1934 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001935 setValue(&I, Tmp);
1936 DAG.setRoot(Tmp.getValue(1));
1937 return 0;
1938 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001939 case Intrinsic::stackrestore: {
1940 SDOperand Tmp = getValue(I.getOperand(1));
1941 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001942 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001943 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001944 case Intrinsic::prefetch:
1945 // FIXME: Currently discarding prefetches.
1946 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001947 }
1948}
1949
1950
Chris Lattner7a60d912005-01-07 07:47:53 +00001951void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001952 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001953 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001954 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001955 if (unsigned IID = F->getIntrinsicID()) {
1956 RenameFn = visitIntrinsicCall(I, IID);
1957 if (!RenameFn)
1958 return;
1959 } else { // Not an LLVM intrinsic.
1960 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001961 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1962 if (I.getNumOperands() == 3 && // Basic sanity checks.
1963 I.getOperand(1)->getType()->isFloatingPoint() &&
1964 I.getType() == I.getOperand(1)->getType() &&
1965 I.getType() == I.getOperand(2)->getType()) {
1966 SDOperand LHS = getValue(I.getOperand(1));
1967 SDOperand RHS = getValue(I.getOperand(2));
1968 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1969 LHS, RHS));
1970 return;
1971 }
1972 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001973 if (I.getNumOperands() == 2 && // Basic sanity checks.
1974 I.getOperand(1)->getType()->isFloatingPoint() &&
1975 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001976 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001977 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1978 return;
1979 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001980 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001981 if (I.getNumOperands() == 2 && // Basic sanity checks.
1982 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001983 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001984 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001985 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1986 return;
1987 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001988 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001989 if (I.getNumOperands() == 2 && // Basic sanity checks.
1990 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001991 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001992 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001993 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1994 return;
1995 }
1996 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001997 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001998 } else if (isa<InlineAsm>(I.getOperand(0))) {
1999 visitInlineAsm(I);
2000 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002001 }
Misha Brukman835702a2005-04-21 22:36:52 +00002002
Chris Lattner18d2b342005-01-08 22:48:57 +00002003 SDOperand Callee;
2004 if (!RenameFn)
2005 Callee = getValue(I.getOperand(0));
2006 else
2007 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002008 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002009 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002010 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2011 Value *Arg = I.getOperand(i);
2012 SDOperand ArgNode = getValue(Arg);
2013 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2014 }
Misha Brukman835702a2005-04-21 22:36:52 +00002015
Nate Begemanf6565252005-03-26 01:29:23 +00002016 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2017 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002018
Chris Lattner1f45cd72005-01-08 19:26:18 +00002019 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002020 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002021 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002022 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002023 setValue(&I, Result.first);
2024 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002025}
2026
Chris Lattner6f87d182006-02-22 22:37:12 +00002027SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002028 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002029 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2030 Chain = Val.getValue(1);
2031 Flag = Val.getValue(2);
2032
2033 // If the result was expanded, copy from the top part.
2034 if (Regs.size() > 1) {
2035 assert(Regs.size() == 2 &&
2036 "Cannot expand to more than 2 elts yet!");
2037 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002038 Chain = Hi.getValue(1);
2039 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002040 if (DAG.getTargetLoweringInfo().isLittleEndian())
2041 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2042 else
2043 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002044 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002045
Chris Lattner705948d2006-06-08 18:22:48 +00002046 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002047 // appropriate type.
2048 if (RegVT == ValueVT)
2049 return Val;
2050
Chris Lattner705948d2006-06-08 18:22:48 +00002051 if (MVT::isInteger(RegVT)) {
2052 if (ValueVT < RegVT)
2053 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2054 else
2055 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2056 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002057 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002058 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002059}
2060
Chris Lattner571d9642006-02-23 19:21:04 +00002061/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2062/// specified value into the registers specified by this object. This uses
2063/// Chain/Flag as the input and updates them for the output Chain/Flag.
2064void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002065 SDOperand &Chain, SDOperand &Flag,
2066 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002067 if (Regs.size() == 1) {
2068 // If there is a single register and the types differ, this must be
2069 // a promotion.
2070 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002071 if (MVT::isInteger(RegVT)) {
2072 if (RegVT < ValueVT)
2073 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2074 else
2075 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2076 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002077 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2078 }
2079 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2080 Flag = Chain.getValue(1);
2081 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002082 std::vector<unsigned> R(Regs);
2083 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2084 std::reverse(R.begin(), R.end());
2085
2086 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002087 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002088 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002089 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002090 Flag = Chain.getValue(1);
2091 }
2092 }
2093}
Chris Lattner6f87d182006-02-22 22:37:12 +00002094
Chris Lattner571d9642006-02-23 19:21:04 +00002095/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2096/// operand list. This adds the code marker and includes the number of
2097/// values added into it.
2098void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002099 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002100 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2101 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2102 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2103}
Chris Lattner6f87d182006-02-22 22:37:12 +00002104
2105/// isAllocatableRegister - If the specified register is safe to allocate,
2106/// i.e. it isn't a stack pointer or some other special register, return the
2107/// register class for the register. Otherwise, return null.
2108static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002109isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2110 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002111 MVT::ValueType FoundVT = MVT::Other;
2112 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002113 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2114 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002115 MVT::ValueType ThisVT = MVT::Other;
2116
Chris Lattnerb1124f32006-02-22 23:09:03 +00002117 const TargetRegisterClass *RC = *RCI;
2118 // If none of the the value types for this register class are valid, we
2119 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002120 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2121 I != E; ++I) {
2122 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002123 // If we have already found this register in a different register class,
2124 // choose the one with the largest VT specified. For example, on
2125 // PowerPC, we favor f64 register classes over f32.
2126 if (FoundVT == MVT::Other ||
2127 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2128 ThisVT = *I;
2129 break;
2130 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002131 }
2132 }
2133
Chris Lattnerbec582f2006-04-02 00:24:45 +00002134 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002135
Chris Lattner6f87d182006-02-22 22:37:12 +00002136 // NOTE: This isn't ideal. In particular, this might allocate the
2137 // frame pointer in functions that need it (due to them not being taken
2138 // out of allocation, because a variable sized allocation hasn't been seen
2139 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002140 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2141 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002142 if (*I == Reg) {
2143 // We found a matching register class. Keep looking at others in case
2144 // we find one with larger registers that this physreg is also in.
2145 FoundRC = RC;
2146 FoundVT = ThisVT;
2147 break;
2148 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002149 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002150 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002151}
2152
2153RegsForValue SelectionDAGLowering::
2154GetRegistersForValue(const std::string &ConstrCode,
2155 MVT::ValueType VT, bool isOutReg, bool isInReg,
2156 std::set<unsigned> &OutputRegs,
2157 std::set<unsigned> &InputRegs) {
2158 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2159 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2160 std::vector<unsigned> Regs;
2161
2162 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2163 MVT::ValueType RegVT;
2164 MVT::ValueType ValueVT = VT;
2165
2166 if (PhysReg.first) {
2167 if (VT == MVT::Other)
2168 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002169
2170 // Get the actual register value type. This is important, because the user
2171 // may have asked for (e.g.) the AX register in i32 type. We need to
2172 // remember that AX is actually i16 to get the right extension.
2173 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002174
2175 // This is a explicit reference to a physical register.
2176 Regs.push_back(PhysReg.first);
2177
2178 // If this is an expanded reference, add the rest of the regs to Regs.
2179 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002180 TargetRegisterClass::iterator I = PhysReg.second->begin();
2181 TargetRegisterClass::iterator E = PhysReg.second->end();
2182 for (; *I != PhysReg.first; ++I)
2183 assert(I != E && "Didn't find reg!");
2184
2185 // Already added the first reg.
2186 --NumRegs; ++I;
2187 for (; NumRegs; --NumRegs, ++I) {
2188 assert(I != E && "Ran out of registers to allocate!");
2189 Regs.push_back(*I);
2190 }
2191 }
2192 return RegsForValue(Regs, RegVT, ValueVT);
2193 }
2194
2195 // This is a reference to a register class. Allocate NumRegs consecutive,
2196 // available, registers from the class.
2197 std::vector<unsigned> RegClassRegs =
2198 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2199
2200 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2201 MachineFunction &MF = *CurMBB->getParent();
2202 unsigned NumAllocated = 0;
2203 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2204 unsigned Reg = RegClassRegs[i];
2205 // See if this register is available.
2206 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2207 (isInReg && InputRegs.count(Reg))) { // Already used.
2208 // Make sure we find consecutive registers.
2209 NumAllocated = 0;
2210 continue;
2211 }
2212
2213 // Check to see if this register is allocatable (i.e. don't give out the
2214 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002215 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002216 if (!RC) {
2217 // Make sure we find consecutive registers.
2218 NumAllocated = 0;
2219 continue;
2220 }
2221
2222 // Okay, this register is good, we can use it.
2223 ++NumAllocated;
2224
2225 // If we allocated enough consecutive
2226 if (NumAllocated == NumRegs) {
2227 unsigned RegStart = (i-NumAllocated)+1;
2228 unsigned RegEnd = i+1;
2229 // Mark all of the allocated registers used.
2230 for (unsigned i = RegStart; i != RegEnd; ++i) {
2231 unsigned Reg = RegClassRegs[i];
2232 Regs.push_back(Reg);
2233 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2234 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2235 }
2236
2237 return RegsForValue(Regs, *RC->vt_begin(), VT);
2238 }
2239 }
2240
2241 // Otherwise, we couldn't allocate enough registers for this.
2242 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002243}
2244
Chris Lattner6f87d182006-02-22 22:37:12 +00002245
Chris Lattner476e67b2006-01-26 22:24:51 +00002246/// visitInlineAsm - Handle a call to an InlineAsm object.
2247///
2248void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2249 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2250
2251 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2252 MVT::Other);
2253
2254 // Note, we treat inline asms both with and without side-effects as the same.
2255 // If an inline asm doesn't have side effects and doesn't access memory, we
2256 // could not choose to not chain it.
2257 bool hasSideEffects = IA->hasSideEffects();
2258
Chris Lattner3a5ed552006-02-01 01:28:23 +00002259 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002260 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002261
2262 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2263 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2264 /// if it is a def of that register.
2265 std::vector<SDOperand> AsmNodeOperands;
2266 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2267 AsmNodeOperands.push_back(AsmStr);
2268
2269 SDOperand Chain = getRoot();
2270 SDOperand Flag;
2271
Chris Lattner1558fc62006-02-01 18:59:47 +00002272 // We fully assign registers here at isel time. This is not optimal, but
2273 // should work. For register classes that correspond to LLVM classes, we
2274 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2275 // over the constraints, collecting fixed registers that we know we can't use.
2276 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002277 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002278 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2279 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2280 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002281
Chris Lattner7ad77df2006-02-22 00:56:39 +00002282 MVT::ValueType OpVT;
2283
2284 // Compute the value type for each operand and add it to ConstraintVTs.
2285 switch (Constraints[i].Type) {
2286 case InlineAsm::isOutput:
2287 if (!Constraints[i].isIndirectOutput) {
2288 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2289 OpVT = TLI.getValueType(I.getType());
2290 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002291 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002292 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2293 OpNum++; // Consumes a call operand.
2294 }
2295 break;
2296 case InlineAsm::isInput:
2297 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2298 OpNum++; // Consumes a call operand.
2299 break;
2300 case InlineAsm::isClobber:
2301 OpVT = MVT::Other;
2302 break;
2303 }
2304
2305 ConstraintVTs.push_back(OpVT);
2306
Chris Lattner6f87d182006-02-22 22:37:12 +00002307 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2308 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002309
Chris Lattner6f87d182006-02-22 22:37:12 +00002310 // Build a list of regs that this operand uses. This always has a single
2311 // element for promoted/expanded operands.
2312 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2313 false, false,
2314 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002315
2316 switch (Constraints[i].Type) {
2317 case InlineAsm::isOutput:
2318 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002319 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002320 // If this is an early-clobber output, it cannot be assigned to the same
2321 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002322 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002323 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002324 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002325 case InlineAsm::isInput:
2326 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002327 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002328 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002329 case InlineAsm::isClobber:
2330 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002331 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2332 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002333 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002334 }
2335 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002336
Chris Lattner5c79f982006-02-21 23:12:12 +00002337 // Loop over all of the inputs, copying the operand values into the
2338 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002339 RegsForValue RetValRegs;
2340 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002341 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002342
Chris Lattner2e56e892006-01-31 02:03:41 +00002343 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002344 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2345 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002346
Chris Lattner3a5ed552006-02-01 01:28:23 +00002347 switch (Constraints[i].Type) {
2348 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002349 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2350 if (ConstraintCode.size() == 1) // not a physreg name.
2351 CTy = TLI.getConstraintType(ConstraintCode[0]);
2352
2353 if (CTy == TargetLowering::C_Memory) {
2354 // Memory output.
2355 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2356
2357 // Check that the operand (the address to store to) isn't a float.
2358 if (!MVT::isInteger(InOperandVal.getValueType()))
2359 assert(0 && "MATCH FAIL!");
2360
2361 if (!Constraints[i].isIndirectOutput)
2362 assert(0 && "MATCH FAIL!");
2363
2364 OpNum++; // Consumes a call operand.
2365
2366 // Extend/truncate to the right pointer type if needed.
2367 MVT::ValueType PtrType = TLI.getPointerTy();
2368 if (InOperandVal.getValueType() < PtrType)
2369 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2370 else if (InOperandVal.getValueType() > PtrType)
2371 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2372
2373 // Add information to the INLINEASM node to know about this output.
2374 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2375 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2376 AsmNodeOperands.push_back(InOperandVal);
2377 break;
2378 }
2379
2380 // Otherwise, this is a register output.
2381 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2382
Chris Lattner6f87d182006-02-22 22:37:12 +00002383 // If this is an early-clobber output, or if there is an input
2384 // constraint that matches this, we need to reserve the input register
2385 // so no other inputs allocate to it.
2386 bool UsesInputRegister = false;
2387 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2388 UsesInputRegister = true;
2389
2390 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002391 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002392 RegsForValue Regs =
2393 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2394 true, UsesInputRegister,
2395 OutputRegs, InputRegs);
2396 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002397
Chris Lattner3a5ed552006-02-01 01:28:23 +00002398 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002399 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002400 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002401 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002402 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002403 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002404 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2405 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002406 OpNum++; // Consumes a call operand.
2407 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002408
2409 // Add information to the INLINEASM node to know that this register is
2410 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002411 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002412 break;
2413 }
2414 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002415 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002416 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002417
Chris Lattner7f5880b2006-02-02 00:25:23 +00002418 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2419 // If this is required to match an output register we have already set,
2420 // just use its register.
2421 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002422
Chris Lattner571d9642006-02-23 19:21:04 +00002423 // Scan until we find the definition we already emitted of this operand.
2424 // When we find it, create a RegsForValue operand.
2425 unsigned CurOp = 2; // The first operand.
2426 for (; OperandNo; --OperandNo) {
2427 // Advance to the next operand.
2428 unsigned NumOps =
2429 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002430 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2431 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002432 "Skipped past definitions?");
2433 CurOp += (NumOps>>3)+1;
2434 }
2435
2436 unsigned NumOps =
2437 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2438 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2439 "Skipped past definitions?");
2440
2441 // Add NumOps>>3 registers to MatchedRegs.
2442 RegsForValue MatchedRegs;
2443 MatchedRegs.ValueVT = InOperandVal.getValueType();
2444 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2445 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2446 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2447 MatchedRegs.Regs.push_back(Reg);
2448 }
2449
2450 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002451 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2452 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002453 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002454 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002455 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002456
2457 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2458 if (ConstraintCode.size() == 1) // not a physreg name.
2459 CTy = TLI.getConstraintType(ConstraintCode[0]);
2460
2461 if (CTy == TargetLowering::C_Other) {
2462 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2463 assert(0 && "MATCH FAIL!");
2464
2465 // Add information to the INLINEASM node to know about this input.
2466 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2467 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2468 AsmNodeOperands.push_back(InOperandVal);
2469 break;
2470 } else if (CTy == TargetLowering::C_Memory) {
2471 // Memory input.
2472
2473 // Check that the operand isn't a float.
2474 if (!MVT::isInteger(InOperandVal.getValueType()))
2475 assert(0 && "MATCH FAIL!");
2476
2477 // Extend/truncate to the right pointer type if needed.
2478 MVT::ValueType PtrType = TLI.getPointerTy();
2479 if (InOperandVal.getValueType() < PtrType)
2480 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2481 else if (InOperandVal.getValueType() > PtrType)
2482 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2483
2484 // Add information to the INLINEASM node to know about this input.
2485 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2486 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2487 AsmNodeOperands.push_back(InOperandVal);
2488 break;
2489 }
2490
2491 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2492
2493 // Copy the input into the appropriate registers.
2494 RegsForValue InRegs =
2495 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2496 false, true, OutputRegs, InputRegs);
2497 // FIXME: should be match fail.
2498 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2499
Evan Chengef9e07d2006-06-15 08:11:54 +00002500 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002501
2502 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002503 break;
2504 }
Chris Lattner571d9642006-02-23 19:21:04 +00002505 case InlineAsm::isClobber: {
2506 RegsForValue ClobberedRegs =
2507 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2508 OutputRegs, InputRegs);
2509 // Add the clobbered value to the operand list, so that the register
2510 // allocator is aware that the physreg got clobbered.
2511 if (!ClobberedRegs.Regs.empty())
2512 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002513 break;
2514 }
Chris Lattner571d9642006-02-23 19:21:04 +00002515 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002516 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002517
2518 // Finish up input operands.
2519 AsmNodeOperands[0] = Chain;
2520 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2521
Chris Lattnerbd887772006-08-14 23:53:35 +00002522 Chain = DAG.getNode(ISD::INLINEASM,
2523 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002524 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002525 Flag = Chain.getValue(1);
2526
Chris Lattner2e56e892006-01-31 02:03:41 +00002527 // If this asm returns a register value, copy the result from that register
2528 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002529 if (!RetValRegs.Regs.empty())
2530 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002531
Chris Lattner2e56e892006-01-31 02:03:41 +00002532 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2533
2534 // Process indirect outputs, first output all of the flagged copies out of
2535 // physregs.
2536 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002537 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002538 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002539 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2540 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002541 }
2542
2543 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002544 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002545 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002546 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002547 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002548 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002549 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002550 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2551 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002552 DAG.setRoot(Chain);
2553}
2554
2555
Chris Lattner7a60d912005-01-07 07:47:53 +00002556void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2557 SDOperand Src = getValue(I.getOperand(0));
2558
2559 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002560
2561 if (IntPtr < Src.getValueType())
2562 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2563 else if (IntPtr > Src.getValueType())
2564 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002565
2566 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002567 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002568 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2569 Src, getIntPtrConstant(ElementSize));
2570
2571 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002572 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002573
2574 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002575 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002576 DAG.getExternalSymbol("malloc", IntPtr),
2577 Args, DAG);
2578 setValue(&I, Result.first); // Pointers always fit in registers
2579 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002580}
2581
2582void SelectionDAGLowering::visitFree(FreeInst &I) {
2583 std::vector<std::pair<SDOperand, const Type*> > Args;
2584 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002585 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002586 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002587 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002588 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002589 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2590 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002591}
2592
Chris Lattner13d7c252005-08-26 20:54:47 +00002593// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2594// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2595// instructions are special in various ways, which require special support to
2596// insert. The specified MachineInstr is created but not inserted into any
2597// basic blocks, and the scheduler passes ownership of it to this method.
2598MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2599 MachineBasicBlock *MBB) {
2600 std::cerr << "If a target marks an instruction with "
2601 "'usesCustomDAGSchedInserter', it must implement "
2602 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2603 abort();
2604 return 0;
2605}
2606
Chris Lattner58cfd792005-01-09 00:00:49 +00002607void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002608 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2609 getValue(I.getOperand(1)),
2610 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002611}
2612
2613void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002614 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2615 getValue(I.getOperand(0)),
2616 DAG.getSrcValue(I.getOperand(0)));
2617 setValue(&I, V);
2618 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002619}
2620
2621void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002622 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2623 getValue(I.getOperand(1)),
2624 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002625}
2626
2627void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002628 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2629 getValue(I.getOperand(1)),
2630 getValue(I.getOperand(2)),
2631 DAG.getSrcValue(I.getOperand(1)),
2632 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002633}
2634
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002635/// TargetLowering::LowerArguments - This is the default LowerArguments
2636/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002637/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2638/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002639std::vector<SDOperand>
2640TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2641 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2642 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002643 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002644 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2645 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2646
2647 // Add one result value for each formal argument.
2648 std::vector<MVT::ValueType> RetVals;
2649 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2650 MVT::ValueType VT = getValueType(I->getType());
2651
2652 switch (getTypeAction(VT)) {
2653 default: assert(0 && "Unknown type action!");
2654 case Legal:
2655 RetVals.push_back(VT);
2656 break;
2657 case Promote:
2658 RetVals.push_back(getTypeToTransformTo(VT));
2659 break;
2660 case Expand:
2661 if (VT != MVT::Vector) {
2662 // If this is a large integer, it needs to be broken up into small
2663 // integers. Figure out what the destination type is and how many small
2664 // integers it turns into.
2665 MVT::ValueType NVT = getTypeToTransformTo(VT);
2666 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2667 for (unsigned i = 0; i != NumVals; ++i)
2668 RetVals.push_back(NVT);
2669 } else {
2670 // Otherwise, this is a vector type. We only support legal vectors
2671 // right now.
2672 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2673 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002674
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002675 // Figure out if there is a Packed type corresponding to this Vector
2676 // type. If so, convert to the packed type.
2677 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2678 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2679 RetVals.push_back(TVT);
2680 } else {
2681 assert(0 && "Don't support illegal by-val vector arguments yet!");
2682 }
2683 }
2684 break;
2685 }
2686 }
Evan Cheng9618df12006-04-25 23:03:35 +00002687
Chris Lattner3d826992006-05-16 06:45:34 +00002688 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002689
2690 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002691 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2692 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002693 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002694
2695 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002696
2697 // Set up the return result vector.
2698 Ops.clear();
2699 unsigned i = 0;
2700 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2701 MVT::ValueType VT = getValueType(I->getType());
2702
2703 switch (getTypeAction(VT)) {
2704 default: assert(0 && "Unknown type action!");
2705 case Legal:
2706 Ops.push_back(SDOperand(Result, i++));
2707 break;
2708 case Promote: {
2709 SDOperand Op(Result, i++);
2710 if (MVT::isInteger(VT)) {
2711 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2712 : ISD::AssertZext;
2713 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2714 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2715 } else {
2716 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2717 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2718 }
2719 Ops.push_back(Op);
2720 break;
2721 }
2722 case Expand:
2723 if (VT != MVT::Vector) {
2724 // If this is a large integer, it needs to be reassembled from small
2725 // integers. Figure out what the source elt type is and how many small
2726 // integers it is.
2727 MVT::ValueType NVT = getTypeToTransformTo(VT);
2728 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2729 if (NumVals == 2) {
2730 SDOperand Lo = SDOperand(Result, i++);
2731 SDOperand Hi = SDOperand(Result, i++);
2732
2733 if (!isLittleEndian())
2734 std::swap(Lo, Hi);
2735
2736 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2737 } else {
2738 // Value scalarized into many values. Unimp for now.
2739 assert(0 && "Cannot expand i64 -> i16 yet!");
2740 }
2741 } else {
2742 // Otherwise, this is a vector type. We only support legal vectors
2743 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002744 const PackedType *PTy = cast<PackedType>(I->getType());
2745 unsigned NumElems = PTy->getNumElements();
2746 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002747
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002748 // Figure out if there is a Packed type corresponding to this Vector
2749 // type. If so, convert to the packed type.
2750 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002751 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002752 SDOperand N = SDOperand(Result, i++);
2753 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002754 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2755 DAG.getConstant(NumElems, MVT::i32),
2756 DAG.getValueType(getValueType(EltTy)));
2757 Ops.push_back(N);
2758 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002759 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002760 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002761 }
2762 }
2763 break;
2764 }
2765 }
2766 return Ops;
2767}
2768
Chris Lattneraaa23d92006-05-16 22:53:20 +00002769
2770/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2771/// implementation, which just inserts an ISD::CALL node, which is later custom
2772/// lowered by the target to something concrete. FIXME: When all targets are
2773/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2774std::pair<SDOperand, SDOperand>
2775TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2776 unsigned CallingConv, bool isTailCall,
2777 SDOperand Callee,
2778 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002779 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002780 Ops.push_back(Chain); // Op#0 - Chain
2781 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2782 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2783 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2784 Ops.push_back(Callee);
2785
2786 // Handle all of the outgoing arguments.
2787 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2788 MVT::ValueType VT = getValueType(Args[i].second);
2789 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002790 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002791 switch (getTypeAction(VT)) {
2792 default: assert(0 && "Unknown type action!");
2793 case Legal:
2794 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002795 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002796 break;
2797 case Promote:
2798 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002799 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002800 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2801 } else {
2802 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2803 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2804 }
2805 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002806 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002807 break;
2808 case Expand:
2809 if (VT != MVT::Vector) {
2810 // If this is a large integer, it needs to be broken down into small
2811 // integers. Figure out what the source elt type is and how many small
2812 // integers it is.
2813 MVT::ValueType NVT = getTypeToTransformTo(VT);
2814 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2815 if (NumVals == 2) {
2816 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2817 DAG.getConstant(0, getPointerTy()));
2818 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2819 DAG.getConstant(1, getPointerTy()));
2820 if (!isLittleEndian())
2821 std::swap(Lo, Hi);
2822
2823 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002824 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002825 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002826 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002827 } else {
2828 // Value scalarized into many values. Unimp for now.
2829 assert(0 && "Cannot expand i64 -> i16 yet!");
2830 }
2831 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002832 // Otherwise, this is a vector type. We only support legal vectors
2833 // right now.
2834 const PackedType *PTy = cast<PackedType>(Args[i].second);
2835 unsigned NumElems = PTy->getNumElements();
2836 const Type *EltTy = PTy->getElementType();
2837
2838 // Figure out if there is a Packed type corresponding to this Vector
2839 // type. If so, convert to the packed type.
2840 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002841 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2842 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2843 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2844 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002845 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002846 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002847 assert(0 && "Don't support illegal by-val vector call args yet!");
2848 abort();
2849 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002850 }
2851 break;
2852 }
2853 }
2854
2855 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002856 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002857
2858 if (RetTy != Type::VoidTy) {
2859 MVT::ValueType VT = getValueType(RetTy);
2860 switch (getTypeAction(VT)) {
2861 default: assert(0 && "Unknown type action!");
2862 case Legal:
2863 RetTys.push_back(VT);
2864 break;
2865 case Promote:
2866 RetTys.push_back(getTypeToTransformTo(VT));
2867 break;
2868 case Expand:
2869 if (VT != MVT::Vector) {
2870 // If this is a large integer, it needs to be reassembled from small
2871 // integers. Figure out what the source elt type is and how many small
2872 // integers it is.
2873 MVT::ValueType NVT = getTypeToTransformTo(VT);
2874 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2875 for (unsigned i = 0; i != NumVals; ++i)
2876 RetTys.push_back(NVT);
2877 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002878 // Otherwise, this is a vector type. We only support legal vectors
2879 // right now.
2880 const PackedType *PTy = cast<PackedType>(RetTy);
2881 unsigned NumElems = PTy->getNumElements();
2882 const Type *EltTy = PTy->getElementType();
2883
2884 // Figure out if there is a Packed type corresponding to this Vector
2885 // type. If so, convert to the packed type.
2886 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2887 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2888 RetTys.push_back(TVT);
2889 } else {
2890 assert(0 && "Don't support illegal by-val vector call results yet!");
2891 abort();
2892 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002893 }
2894 }
2895 }
2896
2897 RetTys.push_back(MVT::Other); // Always has a chain.
2898
2899 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002900 SDOperand Res = DAG.getNode(ISD::CALL,
2901 DAG.getVTList(&RetTys[0], RetTys.size()),
2902 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002903
2904 // This returns a pair of operands. The first element is the
2905 // return value for the function (if RetTy is not VoidTy). The second
2906 // element is the outgoing token chain.
2907 SDOperand ResVal;
2908 if (RetTys.size() != 1) {
2909 MVT::ValueType VT = getValueType(RetTy);
2910 if (RetTys.size() == 2) {
2911 ResVal = Res;
2912
2913 // If this value was promoted, truncate it down.
2914 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002915 if (VT == MVT::Vector) {
2916 // Insert a VBITCONVERT to convert from the packed result type to the
2917 // MVT::Vector type.
2918 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2919 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2920
2921 // Figure out if there is a Packed type corresponding to this Vector
2922 // type. If so, convert to the packed type.
2923 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2924 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002925 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2926 // "N x PTyElementVT" MVT::Vector type.
2927 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002928 DAG.getConstant(NumElems, MVT::i32),
2929 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002930 } else {
2931 abort();
2932 }
2933 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002934 unsigned AssertOp = RetTy->isSigned() ?
2935 ISD::AssertSext : ISD::AssertZext;
2936 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2937 DAG.getValueType(VT));
2938 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2939 } else {
2940 assert(MVT::isFloatingPoint(VT));
2941 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2942 }
2943 }
2944 } else if (RetTys.size() == 3) {
2945 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2946 Res.getValue(0), Res.getValue(1));
2947
2948 } else {
2949 assert(0 && "Case not handled yet!");
2950 }
2951 }
2952
2953 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2954}
2955
2956
2957
Chris Lattner58cfd792005-01-09 00:00:49 +00002958// It is always conservatively correct for llvm.returnaddress and
2959// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002960//
2961// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2962// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002963std::pair<SDOperand, SDOperand>
2964TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2965 unsigned Depth, SelectionDAG &DAG) {
2966 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002967}
2968
Chris Lattner29dcc712005-05-14 05:50:48 +00002969SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002970 assert(0 && "LowerOperation not implemented for this target!");
2971 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002972 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002973}
2974
Nate Begeman595ec732006-01-28 03:14:31 +00002975SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2976 SelectionDAG &DAG) {
2977 assert(0 && "CustomPromoteOperation not implemented for this target!");
2978 abort();
2979 return SDOperand();
2980}
2981
Chris Lattner58cfd792005-01-09 00:00:49 +00002982void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002983 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00002984 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002985 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002986 setValue(&I, Result.first);
2987 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002988}
2989
Evan Cheng6781b6e2006-02-15 21:59:04 +00002990/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002991/// operand.
2992static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002993 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002994 MVT::ValueType CurVT = VT;
2995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2996 uint64_t Val = C->getValue() & 255;
2997 unsigned Shift = 8;
2998 while (CurVT != MVT::i8) {
2999 Val = (Val << Shift) | Val;
3000 Shift <<= 1;
3001 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003002 }
3003 return DAG.getConstant(Val, VT);
3004 } else {
3005 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3006 unsigned Shift = 8;
3007 while (CurVT != MVT::i8) {
3008 Value =
3009 DAG.getNode(ISD::OR, VT,
3010 DAG.getNode(ISD::SHL, VT, Value,
3011 DAG.getConstant(Shift, MVT::i8)), Value);
3012 Shift <<= 1;
3013 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003014 }
3015
3016 return Value;
3017 }
3018}
3019
Evan Cheng6781b6e2006-02-15 21:59:04 +00003020/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3021/// used when a memcpy is turned into a memset when the source is a constant
3022/// string ptr.
3023static SDOperand getMemsetStringVal(MVT::ValueType VT,
3024 SelectionDAG &DAG, TargetLowering &TLI,
3025 std::string &Str, unsigned Offset) {
3026 MVT::ValueType CurVT = VT;
3027 uint64_t Val = 0;
3028 unsigned MSB = getSizeInBits(VT) / 8;
3029 if (TLI.isLittleEndian())
3030 Offset = Offset + MSB - 1;
3031 for (unsigned i = 0; i != MSB; ++i) {
3032 Val = (Val << 8) | Str[Offset];
3033 Offset += TLI.isLittleEndian() ? -1 : 1;
3034 }
3035 return DAG.getConstant(Val, VT);
3036}
3037
Evan Cheng81fcea82006-02-14 08:22:34 +00003038/// getMemBasePlusOffset - Returns base and offset node for the
3039static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3040 SelectionDAG &DAG, TargetLowering &TLI) {
3041 MVT::ValueType VT = Base.getValueType();
3042 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3043}
3044
Evan Chengdb2a7a72006-02-14 20:12:38 +00003045/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003046/// to replace the memset / memcpy is below the threshold. It also returns the
3047/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003048static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3049 unsigned Limit, uint64_t Size,
3050 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003051 MVT::ValueType VT;
3052
3053 if (TLI.allowsUnalignedMemoryAccesses()) {
3054 VT = MVT::i64;
3055 } else {
3056 switch (Align & 7) {
3057 case 0:
3058 VT = MVT::i64;
3059 break;
3060 case 4:
3061 VT = MVT::i32;
3062 break;
3063 case 2:
3064 VT = MVT::i16;
3065 break;
3066 default:
3067 VT = MVT::i8;
3068 break;
3069 }
3070 }
3071
Evan Chengd5026102006-02-14 09:11:59 +00003072 MVT::ValueType LVT = MVT::i64;
3073 while (!TLI.isTypeLegal(LVT))
3074 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3075 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003076
Evan Chengd5026102006-02-14 09:11:59 +00003077 if (VT > LVT)
3078 VT = LVT;
3079
Evan Cheng04514992006-02-14 23:05:54 +00003080 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003081 while (Size != 0) {
3082 unsigned VTSize = getSizeInBits(VT) / 8;
3083 while (VTSize > Size) {
3084 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003085 VTSize >>= 1;
3086 }
Evan Chengd5026102006-02-14 09:11:59 +00003087 assert(MVT::isInteger(VT));
3088
3089 if (++NumMemOps > Limit)
3090 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003091 MemOps.push_back(VT);
3092 Size -= VTSize;
3093 }
Evan Chengd5026102006-02-14 09:11:59 +00003094
3095 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003096}
3097
Chris Lattner875def92005-01-11 05:56:49 +00003098void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003099 SDOperand Op1 = getValue(I.getOperand(1));
3100 SDOperand Op2 = getValue(I.getOperand(2));
3101 SDOperand Op3 = getValue(I.getOperand(3));
3102 SDOperand Op4 = getValue(I.getOperand(4));
3103 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3104 if (Align == 0) Align = 1;
3105
3106 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3107 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003108
3109 // Expand memset / memcpy to a series of load / store ops
3110 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003111 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003112 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003113 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003114 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003115 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3116 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003117 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003118 unsigned Offset = 0;
3119 for (unsigned i = 0; i < NumMemOps; i++) {
3120 MVT::ValueType VT = MemOps[i];
3121 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003122 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003123 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003124 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003125 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003126 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003127 Offset += VTSize;
3128 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003129 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003130 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003131 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003132 case ISD::MEMCPY: {
3133 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3134 Size->getValue(), Align, TLI)) {
3135 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003136 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003137 GlobalAddressSDNode *G = NULL;
3138 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003139 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003140
3141 if (Op2.getOpcode() == ISD::GlobalAddress)
3142 G = cast<GlobalAddressSDNode>(Op2);
3143 else if (Op2.getOpcode() == ISD::ADD &&
3144 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3145 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3146 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003147 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003148 }
3149 if (G) {
3150 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003151 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00003152 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003153 if (!Str.empty()) {
3154 CopyFromStr = true;
3155 SrcOff += SrcDelta;
3156 }
3157 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003158 }
3159
Evan Chenge2038bd2006-02-15 01:54:51 +00003160 for (unsigned i = 0; i < NumMemOps; i++) {
3161 MVT::ValueType VT = MemOps[i];
3162 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003163 SDOperand Value, Chain, Store;
3164
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003165 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003166 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3167 Chain = getRoot();
3168 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003169 DAG.getStore(Chain, Value,
3170 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003171 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003172 } else {
3173 Value = DAG.getLoad(VT, getRoot(),
3174 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003175 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003176 Chain = Value.getValue(1);
3177 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003178 DAG.getStore(Chain, Value,
3179 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003180 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003181 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003182 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003183 SrcOff += VTSize;
3184 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003185 }
3186 }
3187 break;
3188 }
3189 }
3190
3191 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003192 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3193 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003194 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003195 }
3196 }
3197
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003198 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003199}
3200
Chris Lattner875def92005-01-11 05:56:49 +00003201//===----------------------------------------------------------------------===//
3202// SelectionDAGISel code
3203//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003204
3205unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3206 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3207}
3208
Chris Lattnerc9950c12005-08-17 06:37:43 +00003209void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003210 // FIXME: we only modify the CFG to split critical edges. This
3211 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003212 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003213}
Chris Lattner7a60d912005-01-07 07:47:53 +00003214
Chris Lattner35397782005-12-05 07:10:48 +00003215
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003216/// OptimizeNoopCopyExpression - We have determined that the specified cast
3217/// instruction is a noop copy (e.g. it's casting from one pointer type to
3218/// another, int->uint, or int->sbyte on PPC.
3219///
3220/// Return true if any changes are made.
3221static bool OptimizeNoopCopyExpression(CastInst *CI) {
3222 BasicBlock *DefBB = CI->getParent();
3223
3224 /// InsertedCasts - Only insert a cast in each block once.
3225 std::map<BasicBlock*, CastInst*> InsertedCasts;
3226
3227 bool MadeChange = false;
3228 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3229 UI != E; ) {
3230 Use &TheUse = UI.getUse();
3231 Instruction *User = cast<Instruction>(*UI);
3232
3233 // Figure out which BB this cast is used in. For PHI's this is the
3234 // appropriate predecessor block.
3235 BasicBlock *UserBB = User->getParent();
3236 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3237 unsigned OpVal = UI.getOperandNo()/2;
3238 UserBB = PN->getIncomingBlock(OpVal);
3239 }
3240
3241 // Preincrement use iterator so we don't invalidate it.
3242 ++UI;
3243
3244 // If this user is in the same block as the cast, don't change the cast.
3245 if (UserBB == DefBB) continue;
3246
3247 // If we have already inserted a cast into this block, use it.
3248 CastInst *&InsertedCast = InsertedCasts[UserBB];
3249
3250 if (!InsertedCast) {
3251 BasicBlock::iterator InsertPt = UserBB->begin();
3252 while (isa<PHINode>(InsertPt)) ++InsertPt;
3253
3254 InsertedCast =
3255 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3256 MadeChange = true;
3257 }
3258
3259 // Replace a use of the cast with a use of the new casat.
3260 TheUse = InsertedCast;
3261 }
3262
3263 // If we removed all uses, nuke the cast.
3264 if (CI->use_empty())
3265 CI->eraseFromParent();
3266
3267 return MadeChange;
3268}
3269
Chris Lattner35397782005-12-05 07:10:48 +00003270/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3271/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003272static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3273 Instruction *GEPI, Value *Ptr,
3274 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003275 if (V) return V; // Already computed.
3276
3277 BasicBlock::iterator InsertPt;
3278 if (BB == GEPI->getParent()) {
3279 // If insert into the GEP's block, insert right after the GEP.
3280 InsertPt = GEPI;
3281 ++InsertPt;
3282 } else {
3283 // Otherwise, insert at the top of BB, after any PHI nodes
3284 InsertPt = BB->begin();
3285 while (isa<PHINode>(InsertPt)) ++InsertPt;
3286 }
3287
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003288 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3289 // BB so that there is only one value live across basic blocks (the cast
3290 // operand).
3291 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3292 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3293 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3294
Chris Lattner35397782005-12-05 07:10:48 +00003295 // Add the offset, cast it to the right type.
3296 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003297 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003298}
3299
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003300/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3301/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3302/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3303/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3304/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3305/// the constant add into a load or store instruction. Additionally, if a user
3306/// is a pointer-pointer cast, we look through it to find its users.
3307static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3308 Constant *PtrOffset, BasicBlock *DefBB,
3309 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003310 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003311 while (!RepPtr->use_empty()) {
3312 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003313
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003314 // If the user is a Pointer-Pointer cast, recurse.
3315 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3316 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003317
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003318 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3319 // could invalidate an iterator.
3320 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3321 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003322 }
3323
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003324 // If this is a load of the pointer, or a store through the pointer, emit
3325 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003326 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003327 if (isa<LoadInst>(User) ||
3328 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3329 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3330 User->getParent(), GEPI,
3331 Ptr, PtrOffset);
3332 } else {
3333 // If this use is not foldable into the addressing mode, use a version
3334 // emitted in the GEP block.
3335 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3336 Ptr, PtrOffset);
3337 }
3338
Chris Lattner21cd9902006-05-06 09:10:37 +00003339 if (GEPI->getType() != RepPtr->getType()) {
3340 BasicBlock::iterator IP = NewVal;
3341 ++IP;
3342 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3343 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003344 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003345 }
3346}
Chris Lattner35397782005-12-05 07:10:48 +00003347
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003348
Chris Lattner35397782005-12-05 07:10:48 +00003349/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3350/// selection, we want to be a bit careful about some things. In particular, if
3351/// we have a GEP instruction that is used in a different block than it is
3352/// defined, the addressing expression of the GEP cannot be folded into loads or
3353/// stores that use it. In this case, decompose the GEP and move constant
3354/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003355static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003356 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003357 // If this GEP is only used inside the block it is defined in, there is no
3358 // need to rewrite it.
3359 bool isUsedOutsideDefBB = false;
3360 BasicBlock *DefBB = GEPI->getParent();
3361 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3362 UI != E; ++UI) {
3363 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3364 isUsedOutsideDefBB = true;
3365 break;
3366 }
3367 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003368 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003369
3370 // If this GEP has no non-zero constant indices, there is nothing we can do,
3371 // ignore it.
3372 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003373 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003374 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3375 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003376 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003377 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003378 hasConstantIndex = true;
3379 break;
3380 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003381 } else {
3382 hasVariableIndex = true;
3383 }
Chris Lattner35397782005-12-05 07:10:48 +00003384 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003385
3386 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3387 if (!hasConstantIndex && !hasVariableIndex) {
3388 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3389 GEPI->getName(), GEPI);
3390 GEPI->replaceAllUsesWith(NC);
3391 GEPI->eraseFromParent();
3392 return true;
3393 }
3394
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003395 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003396 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3397 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003398
3399 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3400 // constant offset (which we now know is non-zero) and deal with it later.
3401 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003402 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003403 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3404 const Type *Ty = GEPI->getOperand(0)->getType();
3405
3406 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3407 E = GEPI->op_end(); OI != E; ++OI) {
3408 Value *Idx = *OI;
3409 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003410 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003411 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003412 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003413 Ty = StTy->getElementType(Field);
3414 } else {
3415 Ty = cast<SequentialType>(Ty)->getElementType();
3416
3417 // Handle constant subscripts.
3418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003419 if (CI->getZExtValue() == 0) continue;
3420 if (CI->getType()->isSigned())
3421 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003422 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003423 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003424 continue;
3425 }
3426
3427 // Ptr = Ptr + Idx * ElementSize;
3428
3429 // Cast Idx to UIntPtrTy if needed.
3430 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3431
Owen Anderson20a631f2006-05-03 01:29:57 +00003432 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003433 // Mask off bits that should not be set.
3434 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003435 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003436
3437 // Multiply by the element size and add to the base.
3438 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3439 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3440 }
3441 }
3442
3443 // Make sure that the offset fits in uintptr_t.
3444 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003445 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003446
3447 // Okay, we have now emitted all of the variable index parts to the BB that
3448 // the GEP is defined in. Loop over all of the using instructions, inserting
3449 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003450 // instruction to use the newly computed value, making GEPI dead. When the
3451 // user is a load or store instruction address, we emit the add into the user
3452 // block, otherwise we use a canonical version right next to the gep (these
3453 // won't be foldable as addresses, so we might as well share the computation).
3454
Chris Lattner21cd9902006-05-06 09:10:37 +00003455 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003456 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003457
3458 // Finally, the GEP is dead, remove it.
3459 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003460
3461 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003462}
3463
Chris Lattnera9caf952006-09-28 06:17:10 +00003464/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3465/// constant operands, and if any of the edges feeding the PHI node are
3466/// critical, split them so that the assignments of a constant to a register
3467/// will not be executed on a path that isn't relevant.
3468void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003469 // The most common case is that this is a PHI node with two incoming
3470 // successors handle this case efficiently, because it is simple.
3471 PHINode *PN = cast<PHINode>(BB->begin());
3472 if (PN->getNumIncomingValues() == 2) {
3473 // If neither edge is critical, we never need to split.
3474 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3475 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3476 return;
3477
3478 BasicBlock::iterator BBI = BB->begin();
3479 while ((PN = dyn_cast<PHINode>(BBI++))) {
3480 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3481 if (isa<Constant>(PN->getIncomingValue(i)))
3482 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3483 }
3484 return;
3485 }
3486
3487 // Otherwise, things are a bit trickier.
3488
3489 // BE SMART HERE.
3490
Chris Lattnera9caf952006-09-28 06:17:10 +00003491 BasicBlock::iterator BBI = BB->begin();
3492 while ((PN = dyn_cast<PHINode>(BBI++))) {
3493 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3494 if (isa<Constant>(PN->getIncomingValue(i)))
3495 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3496 }
3497}
3498
3499
Chris Lattner7a60d912005-01-07 07:47:53 +00003500bool SelectionDAGISel::runOnFunction(Function &Fn) {
3501 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3502 RegMap = MF.getSSARegMap();
3503 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3504
Chris Lattner35397782005-12-05 07:10:48 +00003505 // First, split all critical edges for PHI nodes with incoming values that are
3506 // constants, this way the load of the constant into a vreg will not be placed
3507 // into MBBs that are used some other way.
3508 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003509 // In this pass we also look for GEP and cast instructions that are used
3510 // across basic blocks and rewrite them to improve basic-block-at-a-time
3511 // selection.
3512 //
Chris Lattner35397782005-12-05 07:10:48 +00003513 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003514 bool MadeChange = true;
3515 while (MadeChange) {
3516 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003517 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003518 // If this block has any PHI nodes with constant operands, and if any of the
3519 // edges feeding the PHI node are critical, split them.
3520 if (isa<PHINode>(BB->begin()))
3521 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003522
Chris Lattnera9caf952006-09-28 06:17:10 +00003523 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003524 Instruction *I = BBI++;
3525 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003526 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003527 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003528 // If the source of the cast is a constant, then this should have
3529 // already been constant folded. The only reason NOT to constant fold
3530 // it is if something (e.g. LSR) was careful to place the constant
3531 // evaluation in a block other than then one that uses it (e.g. to hoist
3532 // the address of globals out of a loop). If this is the case, we don't
3533 // want to forward-subst the cast.
3534 if (isa<Constant>(CI->getOperand(0)))
3535 continue;
3536
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003537 // If this is a noop copy, sink it into user blocks to reduce the number
3538 // of virtual registers that must be created and coallesced.
3539 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3540 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3541
3542 // This is an fp<->int conversion?
3543 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3544 continue;
3545
3546 // If this is an extension, it will be a zero or sign extension, which
3547 // isn't a noop.
3548 if (SrcVT < DstVT) continue;
3549
3550 // If these values will be promoted, find out what they will be promoted
3551 // to. This helps us consider truncates on PPC as noop copies when they
3552 // are.
3553 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3554 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3555 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3556 DstVT = TLI.getTypeToTransformTo(DstVT);
3557
3558 // If, after promotion, these are the same types, this is a noop copy.
3559 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003560 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003561 }
3562 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003563 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003564 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003565
Chris Lattner7a60d912005-01-07 07:47:53 +00003566 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3567
3568 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3569 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003570
Chris Lattner7a60d912005-01-07 07:47:53 +00003571 return true;
3572}
3573
Chris Lattnered0110b2006-10-27 21:36:01 +00003574SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3575 unsigned Reg) {
3576 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003577 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003578 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003579 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003580
3581 // If this type is not legal, we must make sure to not create an invalid
3582 // register use.
3583 MVT::ValueType SrcVT = Op.getValueType();
3584 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003585 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003586 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003587 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003588 // Handle copies from generic vectors to registers.
3589 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3590 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3591 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003592
Chris Lattner5fe1f542006-03-31 02:06:56 +00003593 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3594 // MVT::Vector type.
3595 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3596 DAG.getConstant(NE, MVT::i32),
3597 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003598
Chris Lattner5fe1f542006-03-31 02:06:56 +00003599 // Loop over all of the elements of the resultant vector,
3600 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3601 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003602 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003603 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003604 for (unsigned i = 0; i != NE; ++i) {
3605 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003606 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003607 if (PTyElementVT == PTyLegalElementVT) {
3608 // Elements are legal.
3609 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3610 } else if (PTyLegalElementVT > PTyElementVT) {
3611 // Elements are promoted.
3612 if (MVT::isFloatingPoint(PTyLegalElementVT))
3613 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3614 else
3615 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3616 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3617 } else {
3618 // Elements are expanded.
3619 // The src value is expanded into multiple registers.
3620 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003621 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003622 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003623 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003624 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3625 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3626 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003627 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003628 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3629 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003630 } else if (SrcVT < DestVT) {
3631 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003632 if (MVT::isFloatingPoint(SrcVT))
3633 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3634 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003635 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003636 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003637 } else {
3638 // The src value is expanded into multiple registers.
3639 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003640 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003641 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003642 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003643 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003644 return DAG.getCopyToReg(Op, Reg+1, Hi);
3645 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003646}
3647
Chris Lattner16f64df2005-01-17 17:15:02 +00003648void SelectionDAGISel::
3649LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3650 std::vector<SDOperand> &UnorderedChains) {
3651 // If this is the entry block, emit arguments.
3652 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003653 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003654 SDOperand OldRoot = SDL.DAG.getRoot();
3655 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003656
Chris Lattner6871b232005-10-30 19:42:35 +00003657 unsigned a = 0;
3658 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3659 AI != E; ++AI, ++a)
3660 if (!AI->use_empty()) {
3661 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003662
Chris Lattner6871b232005-10-30 19:42:35 +00003663 // If this argument is live outside of the entry block, insert a copy from
3664 // whereever we got it to the vreg that other BB's will reference it as.
3665 if (FuncInfo.ValueMap.count(AI)) {
3666 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003667 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003668 UnorderedChains.push_back(Copy);
3669 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003670 }
Chris Lattner6871b232005-10-30 19:42:35 +00003671
Chris Lattner6871b232005-10-30 19:42:35 +00003672 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003673 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003674 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003675}
3676
Chris Lattner7a60d912005-01-07 07:47:53 +00003677void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3678 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003679 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003680 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003681
3682 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003683
Chris Lattner6871b232005-10-30 19:42:35 +00003684 // Lower any arguments needed in this block if this is the entry block.
3685 if (LLVMBB == &LLVMBB->getParent()->front())
3686 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003687
3688 BB = FuncInfo.MBBMap[LLVMBB];
3689 SDL.setCurrentBasicBlock(BB);
3690
3691 // Lower all of the non-terminator instructions.
3692 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3693 I != E; ++I)
3694 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003695
Chris Lattner7a60d912005-01-07 07:47:53 +00003696 // Ensure that all instructions which are used outside of their defining
3697 // blocks are available as virtual registers.
3698 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003699 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003700 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003701 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003702 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003703 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003704 }
3705
3706 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3707 // ensure constants are generated when needed. Remember the virtual registers
3708 // that need to be added to the Machine PHI nodes as input. We cannot just
3709 // directly add them, because expansion might result in multiple MBB's for one
3710 // BB. As such, the start of the BB might correspond to a different MBB than
3711 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003712 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003713
3714 // Emit constants only once even if used by multiple PHI nodes.
3715 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003716
Chris Lattner7a60d912005-01-07 07:47:53 +00003717 // Check successor nodes PHI nodes that expect a constant to be available from
3718 // this block.
3719 TerminatorInst *TI = LLVMBB->getTerminator();
3720 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3721 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003722 if (!isa<PHINode>(SuccBB->begin())) continue;
3723
Chris Lattner7a60d912005-01-07 07:47:53 +00003724 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3725 PHINode *PN;
3726
3727 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3728 // nodes and Machine PHI nodes, but the incoming operands have not been
3729 // emitted yet.
3730 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003731 (PN = dyn_cast<PHINode>(I)); ++I)
3732 if (!PN->use_empty()) {
3733 unsigned Reg;
3734 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3735 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3736 unsigned &RegOut = ConstantsOut[C];
3737 if (RegOut == 0) {
3738 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003739 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003740 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003741 }
3742 Reg = RegOut;
3743 } else {
3744 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003745 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003746 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003747 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3748 "Didn't codegen value into a register!??");
3749 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003750 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003751 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003752 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003753 }
Misha Brukman835702a2005-04-21 22:36:52 +00003754
Chris Lattner8ea875f2005-01-07 21:34:19 +00003755 // Remember that this register needs to added to the machine PHI node as
3756 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003757 MVT::ValueType VT = TLI.getValueType(PN->getType());
3758 unsigned NumElements;
3759 if (VT != MVT::Vector)
3760 NumElements = TLI.getNumElements(VT);
3761 else {
3762 MVT::ValueType VT1,VT2;
3763 NumElements =
3764 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3765 VT1, VT2);
3766 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003767 for (unsigned i = 0, e = NumElements; i != e; ++i)
3768 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003769 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003770 }
3771 ConstantsOut.clear();
3772
Chris Lattner718b5c22005-01-13 17:59:43 +00003773 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003774 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003775 SDOperand Root = SDL.getRoot();
3776 if (Root.getOpcode() != ISD::EntryToken) {
3777 unsigned i = 0, e = UnorderedChains.size();
3778 for (; i != e; ++i) {
3779 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3780 if (UnorderedChains[i].Val->getOperand(0) == Root)
3781 break; // Don't add the root if we already indirectly depend on it.
3782 }
3783
3784 if (i == e)
3785 UnorderedChains.push_back(Root);
3786 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003787 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3788 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003789 }
3790
Chris Lattner7a60d912005-01-07 07:47:53 +00003791 // Lower the terminator after the copies are emitted.
3792 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003793
Nate Begemaned728c12006-03-27 01:32:24 +00003794 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003795 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003796 SwitchCases.clear();
3797 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003798 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003799
Chris Lattner4108bb02005-01-17 19:43:36 +00003800 // Make sure the root of the DAG is up-to-date.
3801 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003802}
3803
Nate Begemaned728c12006-03-27 01:32:24 +00003804void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003805 // Get alias analysis for load/store combining.
3806 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3807
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003808 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003809 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003810
Chris Lattner7a60d912005-01-07 07:47:53 +00003811 DEBUG(std::cerr << "Lowered selection DAG:\n");
3812 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003813
Chris Lattner7a60d912005-01-07 07:47:53 +00003814 // Second step, hack on the DAG until it only uses operations and types that
3815 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003816 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003817
Chris Lattner7a60d912005-01-07 07:47:53 +00003818 DEBUG(std::cerr << "Legalized selection DAG:\n");
3819 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003820
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003821 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003822 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003823
Evan Cheng739a6a42006-01-21 02:32:06 +00003824 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003825
Chris Lattner5ca31d92005-03-30 01:10:47 +00003826 // Third, instruction select all of the operations to machine code, adding the
3827 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003828 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003829
Chris Lattner7a60d912005-01-07 07:47:53 +00003830 DEBUG(std::cerr << "Selected machine code:\n");
3831 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003832}
Chris Lattner7a60d912005-01-07 07:47:53 +00003833
Nate Begemaned728c12006-03-27 01:32:24 +00003834void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3835 FunctionLoweringInfo &FuncInfo) {
3836 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3837 {
3838 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3839 CurDAG = &DAG;
3840
3841 // First step, lower LLVM code to some DAG. This DAG may use operations and
3842 // types that are not supported by the target.
3843 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3844
3845 // Second step, emit the lowered DAG as machine code.
3846 CodeGenAndEmitDAG(DAG);
3847 }
3848
Chris Lattner5ca31d92005-03-30 01:10:47 +00003849 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003850 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003851 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003852 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3853 MachineInstr *PHI = PHINodesToUpdate[i].first;
3854 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3855 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003856 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003857 PHI->addMachineBasicBlockOperand(BB);
3858 }
3859 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003860 }
Nate Begemaned728c12006-03-27 01:32:24 +00003861
Nate Begeman866b4b42006-04-23 06:26:20 +00003862 // If the JumpTable record is filled in, then we need to emit a jump table.
3863 // Updating the PHI nodes is tricky in this case, since we need to determine
3864 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003865 if (JT.Reg) {
3866 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3867 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3868 CurDAG = &SDAG;
3869 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003870 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003871 // Set the current basic block to the mbb we wish to insert the code into
3872 BB = JT.MBB;
3873 SDL.setCurrentBasicBlock(BB);
3874 // Emit the code
3875 SDL.visitJumpTable(JT);
3876 SDAG.setRoot(SDL.getRoot());
3877 CodeGenAndEmitDAG(SDAG);
3878 // Update PHI Nodes
3879 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3880 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3881 MachineBasicBlock *PHIBB = PHI->getParent();
3882 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3883 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003884 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003885 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003886 PHI->addMachineBasicBlockOperand(RangeBB);
3887 }
3888 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003889 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003890 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003891 }
3892 }
3893 return;
3894 }
3895
Chris Lattner76a7bc82006-10-22 23:00:53 +00003896 // If the switch block involved a branch to one of the actual successors, we
3897 // need to update PHI nodes in that block.
3898 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3899 MachineInstr *PHI = PHINodesToUpdate[i].first;
3900 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3901 "This is not a machine PHI node that we are updating!");
3902 if (BB->isSuccessor(PHI->getParent())) {
3903 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3904 PHI->addMachineBasicBlockOperand(BB);
3905 }
3906 }
3907
Nate Begemaned728c12006-03-27 01:32:24 +00003908 // If we generated any switch lowering information, build and codegen any
3909 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003910 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003911 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3912 CurDAG = &SDAG;
3913 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003914
Nate Begemaned728c12006-03-27 01:32:24 +00003915 // Set the current basic block to the mbb we wish to insert the code into
3916 BB = SwitchCases[i].ThisBB;
3917 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003918
Nate Begemaned728c12006-03-27 01:32:24 +00003919 // Emit the code
3920 SDL.visitSwitchCase(SwitchCases[i]);
3921 SDAG.setRoot(SDL.getRoot());
3922 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003923
3924 // Handle any PHI nodes in successors of this chunk, as if we were coming
3925 // from the original BB before switch expansion. Note that PHI nodes can
3926 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3927 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00003928 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00003929 for (MachineBasicBlock::iterator Phi = BB->begin();
3930 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3931 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3932 for (unsigned pn = 0; ; ++pn) {
3933 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3934 if (PHINodesToUpdate[pn].first == Phi) {
3935 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3936 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3937 break;
3938 }
3939 }
Nate Begemaned728c12006-03-27 01:32:24 +00003940 }
Chris Lattner707339a52006-09-07 01:59:34 +00003941
3942 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00003943 if (BB == SwitchCases[i].FalseBB)
3944 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00003945
3946 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00003947 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00003948 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003949 }
Chris Lattner963ddad2006-10-24 17:57:59 +00003950 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003951 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003952}
Evan Cheng739a6a42006-01-21 02:32:06 +00003953
Jim Laskey95eda5b2006-08-01 14:21:23 +00003954
Evan Cheng739a6a42006-01-21 02:32:06 +00003955//===----------------------------------------------------------------------===//
3956/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3957/// target node in the graph.
3958void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3959 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003960
Jim Laskey29e635d2006-08-02 12:30:23 +00003961 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003962
3963 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003964 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003965 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003966 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003967
Jim Laskey03593f72006-08-01 18:29:48 +00003968 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003969 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003970 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003971}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003972
Chris Lattner47639db2006-03-06 00:22:00 +00003973
Jim Laskey03593f72006-08-01 18:29:48 +00003974HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3975 return new HazardRecognizer();
3976}
3977
Chris Lattner6df34962006-10-11 03:58:02 +00003978//===----------------------------------------------------------------------===//
3979// Helper functions used by the generated instruction selector.
3980//===----------------------------------------------------------------------===//
3981// Calls to these methods are generated by tblgen.
3982
3983/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3984/// the dag combiner simplified the 255, we still want to match. RHS is the
3985/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3986/// specified in the .td file (e.g. 255).
3987bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3988 int64_t DesiredMaskS) {
3989 uint64_t ActualMask = RHS->getValue();
3990 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3991
3992 // If the actual mask exactly matches, success!
3993 if (ActualMask == DesiredMask)
3994 return true;
3995
3996 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3997 if (ActualMask & ~DesiredMask)
3998 return false;
3999
4000 // Otherwise, the DAG Combiner may have proven that the value coming in is
4001 // either already zero or is not demanded. Check for known zero input bits.
4002 uint64_t NeededMask = DesiredMask & ~ActualMask;
4003 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4004 return true;
4005
4006 // TODO: check to see if missing bits are just not demanded.
4007
4008 // Otherwise, this pattern doesn't match.
4009 return false;
4010}
4011
4012/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4013/// the dag combiner simplified the 255, we still want to match. RHS is the
4014/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4015/// specified in the .td file (e.g. 255).
4016bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4017 int64_t DesiredMaskS) {
4018 uint64_t ActualMask = RHS->getValue();
4019 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4020
4021 // If the actual mask exactly matches, success!
4022 if (ActualMask == DesiredMask)
4023 return true;
4024
4025 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4026 if (ActualMask & ~DesiredMask)
4027 return false;
4028
4029 // Otherwise, the DAG Combiner may have proven that the value coming in is
4030 // either already zero or is not demanded. Check for known zero input bits.
4031 uint64_t NeededMask = DesiredMask & ~ActualMask;
4032
4033 uint64_t KnownZero, KnownOne;
4034 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4035
4036 // If all the missing bits in the or are already known to be set, match!
4037 if ((NeededMask & KnownOne) == NeededMask)
4038 return true;
4039
4040 // TODO: check to see if missing bits are just not demanded.
4041
4042 // Otherwise, this pattern doesn't match.
4043 return false;
4044}
4045
Jim Laskey03593f72006-08-01 18:29:48 +00004046
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004047/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4048/// by tblgen. Others should not call it.
4049void SelectionDAGISel::
4050SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4051 std::vector<SDOperand> InOps;
4052 std::swap(InOps, Ops);
4053
4054 Ops.push_back(InOps[0]); // input chain.
4055 Ops.push_back(InOps[1]); // input asm string.
4056
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004057 unsigned i = 2, e = InOps.size();
4058 if (InOps[e-1].getValueType() == MVT::Flag)
4059 --e; // Don't process a flag operand if it is here.
4060
4061 while (i != e) {
4062 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4063 if ((Flags & 7) != 4 /*MEM*/) {
4064 // Just skip over this operand, copying the operands verbatim.
4065 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4066 i += (Flags >> 3) + 1;
4067 } else {
4068 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4069 // Otherwise, this is a memory operand. Ask the target to select it.
4070 std::vector<SDOperand> SelOps;
4071 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4072 std::cerr << "Could not match memory address. Inline asm failure!\n";
4073 exit(1);
4074 }
4075
4076 // Add this to the output node.
4077 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4078 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4079 i += 2;
4080 }
4081 }
4082
4083 // Add the flag input back if present.
4084 if (e != InOps.size())
4085 Ops.push_back(InOps.back());
4086}