blob: dcb2169ae4b73fd8c3f5ddc64cff6119210a551a [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"
Evan Cheng009ea542007-03-16 08:46:27 +000016#include "llvm/Analysis/LoopInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000019#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000028#include "llvm/CodeGen/MachineModuleInfo.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 Lattner90f42382006-11-29 01:12:32 +000037#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattner975f5c92005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000058#else
Chris Lattneref598052006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000060#endif
61
Jim Laskey29e635d2006-08-02 12:30:23 +000062//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 }
255
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 }
Chris Lattner84a03502006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000292 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner49409cb2006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencer09575ba2007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner7a60d912005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner79084302007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000358
Chris Lattner4d9651c2005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemaned728c12006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattner2fbff4d2007-02-13 20:09:07 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner7a60d912005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
Nate Begemaned728c12006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000409
Chris Lattner7a60d912005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000418 }
419
Chris Lattner4108bb02005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000425
Chris Lattner4d9651c2005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000439 }
440
Chris Lattnered0110b2006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner4024c002006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner8471b152006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
Chris Lattner79084302007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000475
Chris Lattner6f87d182006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000481
Chris Lattnered0110b2006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000487 void LowerCallTo(Instruction &I,
488 const Type *CalledValueTy, unsigned CallingConv,
489 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000490
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 // Terminator instructions.
492 void visitRet(ReturnInst &I);
493 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000494 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 void visitUnreachable(UnreachableInst &I) { /* noop */ }
496
Nate Begemaned728c12006-03-27 01:32:24 +0000497 // Helper for visitSwitch
498 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000499 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000500
Chris Lattner7a60d912005-01-07 07:47:53 +0000501 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000502 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000503 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000504 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000505
Reid Spencer2eadb532007-01-21 00:29:26 +0000506 void visitScalarBinary(User &I, unsigned OpCode);
507 void visitVectorBinary(User &I, unsigned OpCode);
508 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000509 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000510 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000511 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000512 visitVectorBinary(I, ISD::VADD);
513 else if (I.getType()->isFloatingPoint())
514 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000515 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000516 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000517 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000518 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000519 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000520 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000521 visitVectorBinary(I, ISD::VMUL);
522 else if (I.getType()->isFloatingPoint())
523 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000524 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000525 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000526 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000527 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
528 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
529 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
530 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
531 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
532 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
533 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
534 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
535 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
536 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000537 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
538 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000539 void visitICmp(User &I);
540 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000541 // Visit the conversion instructions
542 void visitTrunc(User &I);
543 void visitZExt(User &I);
544 void visitSExt(User &I);
545 void visitFPTrunc(User &I);
546 void visitFPExt(User &I);
547 void visitFPToUI(User &I);
548 void visitFPToSI(User &I);
549 void visitUIToFP(User &I);
550 void visitSIToFP(User &I);
551 void visitPtrToInt(User &I);
552 void visitIntToPtr(User &I);
553 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000554
Chris Lattner67271862006-03-29 00:11:43 +0000555 void visitExtractElement(User &I);
556 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000557 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000558
Chris Lattner7a60d912005-01-07 07:47:53 +0000559 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000560 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000561
562 void visitMalloc(MallocInst &I);
563 void visitFree(FreeInst &I);
564 void visitAlloca(AllocaInst &I);
565 void visitLoad(LoadInst &I);
566 void visitStore(StoreInst &I);
567 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
568 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000569 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000570 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000571 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000572
Chris Lattner7a60d912005-01-07 07:47:53 +0000573 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000574 void visitVAArg(VAArgInst &I);
575 void visitVAEnd(CallInst &I);
576 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000577
Chris Lattner875def92005-01-11 05:56:49 +0000578 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000579
580 void visitUserOp1(Instruction &I) {
581 assert(0 && "UserOp1 should not exist at instruction selection time!");
582 abort();
583 }
584 void visitUserOp2(Instruction &I) {
585 assert(0 && "UserOp2 should not exist at instruction selection time!");
586 abort();
587 }
588};
589} // end namespace llvm
590
Chris Lattner8471b152006-03-16 19:57:50 +0000591SDOperand SelectionDAGLowering::getValue(const Value *V) {
592 SDOperand &N = NodeMap[V];
593 if (N.Val) return N;
594
595 const Type *VTy = V->getType();
596 MVT::ValueType VT = TLI.getValueType(VTy);
597 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
599 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000600 SDOperand N1 = NodeMap[V];
601 assert(N1.Val && "visit didn't populate the ValueMap!");
602 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000603 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
604 return N = DAG.getGlobalAddress(GV, VT);
605 } else if (isa<ConstantPointerNull>(C)) {
606 return N = DAG.getConstant(0, TLI.getPointerTy());
607 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000608 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000609 return N = DAG.getNode(ISD::UNDEF, VT);
610
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000611 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000612 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000613 unsigned NumElements = PTy->getNumElements();
614 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
615
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000616 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000617 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
618
619 // Create a VConstant node with generic Vector type.
620 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
621 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000622 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
623 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000624 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
625 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000626 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000627 unsigned NumElements = PTy->getNumElements();
628 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000629
630 // Now that we know the number and type of the elements, push a
631 // Constant or ConstantFP node onto the ops list for each element of
632 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000633 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000634 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000635 for (unsigned i = 0; i != NumElements; ++i)
636 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000637 } else {
638 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
639 SDOperand Op;
640 if (MVT::isFloatingPoint(PVT))
641 Op = DAG.getConstantFP(0, PVT);
642 else
643 Op = DAG.getConstant(0, PVT);
644 Ops.assign(NumElements, Op);
645 }
646
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000647 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000648 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
649 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000650 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
651 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000652 } else {
653 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000654 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000655 }
656 }
657
658 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
659 std::map<const AllocaInst*, int>::iterator SI =
660 FuncInfo.StaticAllocaMap.find(AI);
661 if (SI != FuncInfo.StaticAllocaMap.end())
662 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
663 }
664
Chris Lattner8c504cf2007-02-25 18:40:32 +0000665 unsigned InReg = FuncInfo.ValueMap[V];
666 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000667
668 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000669 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000670 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000671 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000672 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000673 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
674 unsigned NumVals = TLI.getNumElements(VT);
675 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
676 if (NumVals == 1)
677 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
678 else {
679 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
680 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
681 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
682 }
683 } else {
684 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
685 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
686 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
687 N = MVT::isFloatingPoint(VT)
688 ? DAG.getNode(ISD::FP_ROUND, VT, N)
689 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000690 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000691 } else {
692 // Otherwise, if this is a vector, make it available as a generic vector
693 // here.
694 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000695 const VectorType *PTy = cast<VectorType>(VTy);
696 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000697 PTyLegalElementVT);
698
699 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000700 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000701 if (PTyElementVT == PTyLegalElementVT) {
702 // If the value types are legal, just VBUILD the CopyFromReg nodes.
703 for (unsigned i = 0; i != NE; ++i)
704 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
705 PTyElementVT));
706 } else if (PTyElementVT < PTyLegalElementVT) {
707 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
708 for (unsigned i = 0; i != NE; ++i) {
709 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
710 PTyElementVT);
711 if (MVT::isFloatingPoint(PTyElementVT))
712 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
713 else
714 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
715 Ops.push_back(Op);
716 }
717 } else {
718 // If the register was expanded, use BUILD_PAIR.
719 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
720 for (unsigned i = 0; i != NE/2; ++i) {
721 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
722 PTyElementVT);
723 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
726 }
727 }
728
729 Ops.push_back(DAG.getConstant(NE, MVT::i32));
730 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000731 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000732
733 // Finally, use a VBIT_CONVERT to make this available as the appropriate
734 // vector type.
735 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
736 DAG.getConstant(PTy->getNumElements(),
737 MVT::i32),
738 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000739 }
740
741 return N;
742}
743
744
Chris Lattner7a60d912005-01-07 07:47:53 +0000745void SelectionDAGLowering::visitRet(ReturnInst &I) {
746 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000747 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000748 return;
749 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000750 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000751 NewValues.push_back(getRoot());
752 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
753 SDOperand RetOp = getValue(I.getOperand(i));
754
755 // If this is an integer return value, we need to promote it ourselves to
756 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
757 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000758 // FIXME: C calling convention requires the return type to be promoted to
759 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000760 if (MVT::isInteger(RetOp.getValueType()) &&
761 RetOp.getValueType() < MVT::i64) {
762 MVT::ValueType TmpVT;
763 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
764 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
765 else
766 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000767 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000768 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000769 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
770 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000771 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
772 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000773 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000774 }
775 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000776 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000777 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000778 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
779 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000780}
781
Chris Lattnered0110b2006-10-27 21:36:01 +0000782/// ExportFromCurrentBlock - If this condition isn't known to be exported from
783/// the current basic block, add it to ValueMap now so that we'll get a
784/// CopyTo/FromReg.
785void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
786 // No need to export constants.
787 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
788
789 // Already exported?
790 if (FuncInfo.isExportedInst(V)) return;
791
792 unsigned Reg = FuncInfo.InitializeRegForValue(V);
793 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
794}
795
Chris Lattner84a03502006-10-27 23:50:33 +0000796bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
797 const BasicBlock *FromBB) {
798 // The operands of the setcc have to be in this block. We don't know
799 // how to export them from some other block.
800 if (Instruction *VI = dyn_cast<Instruction>(V)) {
801 // Can export from current BB.
802 if (VI->getParent() == FromBB)
803 return true;
804
805 // Is already exported, noop.
806 return FuncInfo.isExportedInst(V);
807 }
808
809 // If this is an argument, we can export it if the BB is the entry block or
810 // if it is already exported.
811 if (isa<Argument>(V)) {
812 if (FromBB == &FromBB->getParent()->getEntryBlock())
813 return true;
814
815 // Otherwise, can only export this if it is already exported.
816 return FuncInfo.isExportedInst(V);
817 }
818
819 // Otherwise, constants can always be exported.
820 return true;
821}
822
Chris Lattnere60ae822006-10-29 21:01:20 +0000823static bool InBlock(const Value *V, const BasicBlock *BB) {
824 if (const Instruction *I = dyn_cast<Instruction>(V))
825 return I->getParent() == BB;
826 return true;
827}
828
Chris Lattnered0110b2006-10-27 21:36:01 +0000829/// FindMergedConditions - If Cond is an expression like
830void SelectionDAGLowering::FindMergedConditions(Value *Cond,
831 MachineBasicBlock *TBB,
832 MachineBasicBlock *FBB,
833 MachineBasicBlock *CurBB,
834 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000835 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000836 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000837
Reid Spencer266e42b2006-12-23 06:05:41 +0000838 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
839 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000840 BOp->getParent() != CurBB->getBasicBlock() ||
841 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
842 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000843 const BasicBlock *BB = CurBB->getBasicBlock();
844
Reid Spencer266e42b2006-12-23 06:05:41 +0000845 // If the leaf of the tree is a comparison, merge the condition into
846 // the caseblock.
847 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
848 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000849 // how to export them from some other block. If this is the first block
850 // of the sequence, no exporting is needed.
851 (CurBB == CurMBB ||
852 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
853 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000854 BOp = cast<Instruction>(Cond);
855 ISD::CondCode Condition;
856 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
857 switch (IC->getPredicate()) {
858 default: assert(0 && "Unknown icmp predicate opcode!");
859 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
860 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
861 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
862 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
863 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
864 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
865 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
866 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
867 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
868 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
869 }
870 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
871 ISD::CondCode FPC, FOC;
872 switch (FC->getPredicate()) {
873 default: assert(0 && "Unknown fcmp predicate opcode!");
874 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
875 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
876 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
877 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
878 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
879 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
880 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
881 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
882 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
883 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
884 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
885 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
886 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
887 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
888 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
889 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
890 }
891 if (FiniteOnlyFPMath())
892 Condition = FOC;
893 else
894 Condition = FPC;
895 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000896 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000897 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000898 }
899
Chris Lattnered0110b2006-10-27 21:36:01 +0000900 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
901 BOp->getOperand(1), TBB, FBB, CurBB);
902 SwitchCases.push_back(CB);
903 return;
904 }
905
906 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000907 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000908 TBB, FBB, CurBB);
909 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000910 return;
911 }
912
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000913
914 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000915 MachineFunction::iterator BBI = CurBB;
916 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
917 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
918
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000919 if (Opc == Instruction::Or) {
920 // Codegen X | Y as:
921 // jmp_if_X TBB
922 // jmp TmpBB
923 // TmpBB:
924 // jmp_if_Y TBB
925 // jmp FBB
926 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000927
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000928 // Emit the LHS condition.
929 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
930
931 // Emit the RHS condition into TmpBB.
932 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
933 } else {
934 assert(Opc == Instruction::And && "Unknown merge op!");
935 // Codegen X & Y as:
936 // jmp_if_X TmpBB
937 // jmp FBB
938 // TmpBB:
939 // jmp_if_Y TBB
940 // jmp FBB
941 //
942 // This requires creation of TmpBB after CurBB.
943
944 // Emit the LHS condition.
945 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
946
947 // Emit the RHS condition into TmpBB.
948 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
949 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000950}
951
Chris Lattner427301f2006-10-31 22:37:42 +0000952/// If the set of cases should be emitted as a series of branches, return true.
953/// If we should emit this as a bunch of and/or'd together conditions, return
954/// false.
955static bool
956ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
957 if (Cases.size() != 2) return true;
958
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000959 // If this is two comparisons of the same values or'd or and'd together, they
960 // will get folded into a single comparison, so don't emit two blocks.
961 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
962 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
963 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
964 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
965 return false;
966 }
967
Chris Lattner427301f2006-10-31 22:37:42 +0000968 return true;
969}
970
Chris Lattner7a60d912005-01-07 07:47:53 +0000971void SelectionDAGLowering::visitBr(BranchInst &I) {
972 // Update machine-CFG edges.
973 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000974
975 // Figure out which block is immediately after the current one.
976 MachineBasicBlock *NextBlock = 0;
977 MachineFunction::iterator BBI = CurMBB;
978 if (++BBI != CurMBB->getParent()->end())
979 NextBlock = BBI;
980
981 if (I.isUnconditional()) {
982 // If this is not a fall-through branch, emit the branch.
983 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000984 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000985 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000986
Chris Lattner963ddad2006-10-24 17:57:59 +0000987 // Update machine-CFG edges.
988 CurMBB->addSuccessor(Succ0MBB);
989
990 return;
991 }
992
993 // If this condition is one of the special cases we handle, do special stuff
994 // now.
995 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000996 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000997
998 // If this is a series of conditions that are or'd or and'd together, emit
999 // this as a sequence of branches instead of setcc's with and/or operations.
1000 // For example, instead of something like:
1001 // cmp A, B
1002 // C = seteq
1003 // cmp D, E
1004 // F = setle
1005 // or C, F
1006 // jnz foo
1007 // Emit:
1008 // cmp A, B
1009 // je foo
1010 // cmp D, E
1011 // jle foo
1012 //
1013 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1014 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001015 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001016 BOp->getOpcode() == Instruction::Or)) {
1017 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001018 // If the compares in later blocks need to use values not currently
1019 // exported from this block, export them now. This block should always
1020 // be the first entry.
1021 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1022
Chris Lattner427301f2006-10-31 22:37:42 +00001023 // Allow some cases to be rejected.
1024 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001025 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1026 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1027 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1028 }
1029
1030 // Emit the branch for this block.
1031 visitSwitchCase(SwitchCases[0]);
1032 SwitchCases.erase(SwitchCases.begin());
1033 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001034 }
1035
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001036 // Okay, we decided not to do this, remove any inserted MBB's and clear
1037 // SwitchCases.
1038 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1039 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1040
Chris Lattner427301f2006-10-31 22:37:42 +00001041 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001042 }
1043 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001044
1045 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001046 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001047 Succ0MBB, Succ1MBB, CurMBB);
1048 // Use visitSwitchCase to actually insert the fast branch sequence for this
1049 // cond branch.
1050 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001051}
1052
Nate Begemaned728c12006-03-27 01:32:24 +00001053/// visitSwitchCase - Emits the necessary code to represent a single node in
1054/// the binary search tree resulting from lowering a switch instruction.
1055void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001056 SDOperand Cond;
1057 SDOperand CondLHS = getValue(CB.CmpLHS);
1058
Chris Lattnered0110b2006-10-27 21:36:01 +00001059 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1060 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001061 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001062 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001063 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001064 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1065 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1066 } else
1067 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001068
1069 // Set NextBlock to be the MBB immediately after the current one, if any.
1070 // This is used to avoid emitting unnecessary branches to the next block.
1071 MachineBasicBlock *NextBlock = 0;
1072 MachineFunction::iterator BBI = CurMBB;
1073 if (++BBI != CurMBB->getParent()->end())
1074 NextBlock = BBI;
1075
1076 // If the lhs block is the next block, invert the condition so that we can
1077 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001078 if (CB.TrueBB == NextBlock) {
1079 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001080 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1081 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1082 }
1083 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001084 DAG.getBasicBlock(CB.TrueBB));
1085 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001086 DAG.setRoot(BrCond);
1087 else
1088 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001089 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001090 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001091 CurMBB->addSuccessor(CB.TrueBB);
1092 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001093}
1094
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001095void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001096 // Emit the code for the jump table
1097 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001098 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1099 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1100 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1101 Table, Index));
1102 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001103}
1104
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001105void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001106 assert(0 && "Should never be visited directly");
1107}
1108void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001109 // Retrieve successors.
1110 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1111 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1112
Jim Laskey14059d92007-02-25 21:43:59 +00001113 if (!AsTerminator) {
1114 // Mark landing pad so that it doesn't get deleted in branch folding.
1115 LandingPad->setIsLandingPad();
1116
1117 // Insert a label before the invoke call to mark the try range.
1118 // This can be used to detect deletion of the invoke via the
1119 // MachineModuleInfo.
1120 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1121 unsigned BeginLabel = MMI->NextLabelID();
1122 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1123 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001124
Jim Laskey14059d92007-02-25 21:43:59 +00001125 LowerCallTo(I, I.getCalledValue()->getType(),
1126 I.getCallingConv(),
1127 false,
1128 getValue(I.getOperand(0)),
1129 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001130
Jim Laskey14059d92007-02-25 21:43:59 +00001131 // Insert a label before the invoke call to mark the try range.
1132 // This can be used to detect deletion of the invoke via the
1133 // MachineModuleInfo.
1134 unsigned EndLabel = MMI->NextLabelID();
1135 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1136 DAG.getConstant(EndLabel, MVT::i32)));
1137
1138 // Inform MachineModuleInfo of range.
1139 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1140
1141 // Update successor info
1142 CurMBB->addSuccessor(Return);
1143 CurMBB->addSuccessor(LandingPad);
1144 } else {
1145 // Drop into normal successor.
1146 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1147 DAG.getBasicBlock(Return)));
1148 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001149}
1150
1151void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1152}
1153
Nate Begemaned728c12006-03-27 01:32:24 +00001154void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1155 // Figure out which block is immediately after the current one.
1156 MachineBasicBlock *NextBlock = 0;
1157 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001158
Nate Begemaned728c12006-03-27 01:32:24 +00001159 if (++BBI != CurMBB->getParent()->end())
1160 NextBlock = BBI;
1161
Chris Lattner6d6fc262006-10-22 21:36:53 +00001162 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1163
Nate Begemaned728c12006-03-27 01:32:24 +00001164 // If there is only the default destination, branch to it if it is not the
1165 // next basic block. Otherwise, just fall through.
1166 if (I.getNumOperands() == 2) {
1167 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001168
Nate Begemaned728c12006-03-27 01:32:24 +00001169 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001170 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001171 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001172 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001173
Chris Lattner6d6fc262006-10-22 21:36:53 +00001174 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001175 return;
1176 }
1177
1178 // If there are any non-default case statements, create a vector of Cases
1179 // representing each one, and sort the vector so that we can efficiently
1180 // create a binary search tree from them.
1181 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001182
Nate Begemaned728c12006-03-27 01:32:24 +00001183 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1184 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1185 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1186 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001187
Nate Begemaned728c12006-03-27 01:32:24 +00001188 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1189
1190 // Get the Value to be switched on and default basic blocks, which will be
1191 // inserted into CaseBlock records, representing basic blocks in the binary
1192 // search tree.
1193 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001194
1195 // Get the MachineFunction which holds the current MBB. This is used during
1196 // emission of jump tables, and when inserting any additional MBBs necessary
1197 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001198 MachineFunction *CurMF = CurMBB->getParent();
1199 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001200
1201 // If the switch has few cases (two or less) emit a series of specific
1202 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001203 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001204 // TODO: If any two of the cases has the same destination, and if one value
1205 // is the same as the other, but has one bit unset that the other has set,
1206 // use bit manipulation to do two compares at once. For example:
1207 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1208
Chris Lattner4c931502006-10-23 18:38:22 +00001209 // Rearrange the case blocks so that the last one falls through if possible.
1210 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1211 // The last case block won't fall through into 'NextBlock' if we emit the
1212 // branches in this order. See if rearranging a case value would help.
1213 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1214 if (Cases[i].second == NextBlock) {
1215 std::swap(Cases[i], Cases.back());
1216 break;
1217 }
1218 }
1219 }
1220
Chris Lattner6d6fc262006-10-22 21:36:53 +00001221 // Create a CaseBlock record representing a conditional branch to
1222 // the Case's target mbb if the value being switched on SV is equal
1223 // to C.
1224 MachineBasicBlock *CurBlock = CurMBB;
1225 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1226 MachineBasicBlock *FallThrough;
1227 if (i != e-1) {
1228 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1229 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1230 } else {
1231 // If the last case doesn't match, go to the default block.
1232 FallThrough = Default;
1233 }
1234
1235 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1236 Cases[i].second, FallThrough, CurBlock);
1237
1238 // If emitting the first comparison, just call visitSwitchCase to emit the
1239 // code into the current block. Otherwise, push the CaseBlock onto the
1240 // vector to be later processed by SDISel, and insert the node's MBB
1241 // before the next MBB.
1242 if (CurBlock == CurMBB)
1243 visitSwitchCase(CB);
1244 else
1245 SwitchCases.push_back(CB);
1246
1247 CurBlock = FallThrough;
1248 }
1249 return;
1250 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001251
Nate Begemand7a19102006-05-08 16:51:36 +00001252 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1253 // target supports indirect branches, then emit a jump table rather than
1254 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001255 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1256 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001257 Cases.size() > 5) {
Chris Lattner1cf84d22007-02-14 07:18:16 +00001258 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1259 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001260 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1261
Nate Begemand7a19102006-05-08 16:51:36 +00001262 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001263 // Create a new basic block to hold the code for loading the address
1264 // of the jump table, and jumping to it. Update successor information;
1265 // we will either branch to the default case for the switch, or the jump
1266 // table.
1267 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1268 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1269 CurMBB->addSuccessor(Default);
1270 CurMBB->addSuccessor(JumpTableBB);
1271
1272 // Subtract the lowest switch case value from the value being switched on
1273 // and conditional branch to default mbb if the result is greater than the
1274 // difference between smallest and largest cases.
1275 SDOperand SwitchOp = getValue(SV);
1276 MVT::ValueType VT = SwitchOp.getValueType();
1277 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1278 DAG.getConstant(First, VT));
1279
1280 // The SDNode we just created, which holds the value being switched on
1281 // minus the the smallest case value, needs to be copied to a virtual
1282 // register so it can be used as an index into the jump table in a
1283 // subsequent basic block. This value may be smaller or larger than the
1284 // target's pointer type, and therefore require extension or truncating.
1285 if (VT > TLI.getPointerTy())
1286 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1287 else
1288 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001289
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001290 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1291 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1292
1293 // Emit the range check for the jump table, and branch to the default
1294 // block for the switch statement if the value being switched on exceeds
1295 // the largest case in the switch.
1296 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1297 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1298 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1299 DAG.getBasicBlock(Default)));
1300
Nate Begemandf488392006-05-03 03:48:02 +00001301 // Build a vector of destination BBs, corresponding to each target
1302 // of the jump table. If the value of the jump table slot corresponds to
1303 // a case statement, push the case's BB onto the vector, otherwise, push
1304 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001305 std::vector<MachineBasicBlock*> DestBBs;
Chris Lattnerab1812f2007-02-14 07:34:56 +00001306 int64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001307 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Chris Lattner1cf84d22007-02-14 07:18:16 +00001308 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001309 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001310 ++ii;
1311 } else {
1312 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001313 }
Nate Begemandf488392006-05-03 03:48:02 +00001314
Chris Lattner84a03502006-10-27 23:50:33 +00001315 // Update successor info. Add one edge to each unique successor.
1316 // Vector bool would be better, but vector<bool> is really slow.
1317 std::vector<unsigned char> SuccsHandled;
1318 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1319
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001320 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001321 E = DestBBs.end(); I != E; ++I) {
1322 if (!SuccsHandled[(*I)->getNumber()]) {
1323 SuccsHandled[(*I)->getNumber()] = true;
1324 JumpTableBB->addSuccessor(*I);
1325 }
1326 }
Nate Begemandf488392006-05-03 03:48:02 +00001327
1328 // Create a jump table index for this jump table, or return an existing
1329 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001330 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1331
1332 // Set the jump table information so that we can codegen it as a second
1333 // MachineBasicBlock
1334 JT.Reg = JumpTableReg;
1335 JT.JTI = JTI;
1336 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001337 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001338 return;
1339 }
1340 }
Nate Begemaned728c12006-03-27 01:32:24 +00001341
1342 // Push the initial CaseRec onto the worklist
1343 std::vector<CaseRec> CaseVec;
1344 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1345
1346 while (!CaseVec.empty()) {
1347 // Grab a record representing a case range to process off the worklist
1348 CaseRec CR = CaseVec.back();
1349 CaseVec.pop_back();
1350
1351 // Size is the number of Cases represented by this range. If Size is 1,
1352 // then we are processing a leaf of the binary search tree. Otherwise,
1353 // we need to pick a pivot, and push left and right ranges onto the
1354 // worklist.
1355 unsigned Size = CR.Range.second - CR.Range.first;
1356
1357 if (Size == 1) {
1358 // Create a CaseBlock record representing a conditional branch to
1359 // the Case's target mbb if the value being switched on SV is equal
1360 // to C. Otherwise, branch to default.
1361 Constant *C = CR.Range.first->first;
1362 MachineBasicBlock *Target = CR.Range.first->second;
1363 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1364 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001365
Nate Begemaned728c12006-03-27 01:32:24 +00001366 // If the MBB representing the leaf node is the current MBB, then just
1367 // call visitSwitchCase to emit the code into the current block.
1368 // Otherwise, push the CaseBlock onto the vector to be later processed
1369 // by SDISel, and insert the node's MBB before the next MBB.
1370 if (CR.CaseBB == CurMBB)
1371 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001372 else
Nate Begemaned728c12006-03-27 01:32:24 +00001373 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001374 } else {
1375 // split case range at pivot
1376 CaseItr Pivot = CR.Range.first + (Size / 2);
1377 CaseRange LHSR(CR.Range.first, Pivot);
1378 CaseRange RHSR(Pivot, CR.Range.second);
1379 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001380 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001381
Nate Begemaned728c12006-03-27 01:32:24 +00001382 // We know that we branch to the LHS if the Value being switched on is
1383 // less than the Pivot value, C. We use this to optimize our binary
1384 // tree a bit, by recognizing that if SV is greater than or equal to the
1385 // LHS's Case Value, and that Case Value is exactly one less than the
1386 // Pivot's Value, then we can branch directly to the LHS's Target,
1387 // rather than creating a leaf node for it.
1388 if ((LHSR.second - LHSR.first) == 1 &&
1389 LHSR.first->first == CR.GE &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001390 cast<ConstantInt>(C)->getZExtValue() ==
1391 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001392 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001393 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001394 TrueBB = new MachineBasicBlock(LLVMBB);
1395 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1396 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001397 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001398
Nate Begemaned728c12006-03-27 01:32:24 +00001399 // Similar to the optimization above, if the Value being switched on is
1400 // known to be less than the Constant CR.LT, and the current Case Value
1401 // is CR.LT - 1, then we can branch directly to the target block for
1402 // the current Case Value, rather than emitting a RHS leaf node for it.
1403 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001404 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1405 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001406 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001407 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001408 FalseBB = new MachineBasicBlock(LLVMBB);
1409 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1410 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001411 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001412
Nate Begemaned728c12006-03-27 01:32:24 +00001413 // Create a CaseBlock record representing a conditional branch to
1414 // the LHS node if the value being switched on SV is less than C.
1415 // Otherwise, branch to LHS.
Chris Lattner1cf84d22007-02-14 07:18:16 +00001416 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1417 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001418
Nate Begemaned728c12006-03-27 01:32:24 +00001419 if (CR.CaseBB == CurMBB)
1420 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001421 else
Nate Begemaned728c12006-03-27 01:32:24 +00001422 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001423 }
1424 }
1425}
1426
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001427void SelectionDAGLowering::visitSub(User &I) {
1428 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001429 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001430 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001431 visitVectorBinary(I, ISD::VSUB);
1432 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001433 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1434 if (CFP->isExactlyValue(-0.0)) {
1435 SDOperand Op2 = getValue(I.getOperand(1));
1436 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1437 return;
1438 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001439 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001440 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001441 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001442}
1443
Reid Spencer2eadb532007-01-21 00:29:26 +00001444void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001445 SDOperand Op1 = getValue(I.getOperand(0));
1446 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001447
1448 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001449}
1450
Reid Spencer2eadb532007-01-21 00:29:26 +00001451void
1452SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001453 assert(isa<VectorType>(I.getType()));
1454 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001455 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001456
Reid Spencer2eadb532007-01-21 00:29:26 +00001457 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1458 getValue(I.getOperand(0)),
1459 getValue(I.getOperand(1)),
1460 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1461 Typ));
1462}
1463
1464void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1465 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001466 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001467 visitVectorBinary(I, VectorOp);
1468 else
1469 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001470}
Chris Lattner96c26752005-01-19 22:31:21 +00001471
Nate Begeman127321b2005-11-18 07:42:56 +00001472void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1473 SDOperand Op1 = getValue(I.getOperand(0));
1474 SDOperand Op2 = getValue(I.getOperand(1));
1475
Reid Spencer2341c222007-02-02 02:16:23 +00001476 if (TLI.getShiftAmountTy() < Op2.getValueType())
1477 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1478 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1479 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001480
Chris Lattner7a60d912005-01-07 07:47:53 +00001481 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1482}
1483
Reid Spencerd9436b62006-11-20 01:22:35 +00001484void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001485 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1486 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1487 predicate = IC->getPredicate();
1488 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1489 predicate = ICmpInst::Predicate(IC->getPredicate());
1490 SDOperand Op1 = getValue(I.getOperand(0));
1491 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001492 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001493 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001494 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1495 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1496 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1497 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1498 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1499 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1500 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1501 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1502 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1503 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1504 default:
1505 assert(!"Invalid ICmp predicate value");
1506 Opcode = ISD::SETEQ;
1507 break;
1508 }
1509 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1510}
1511
1512void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001513 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1514 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1515 predicate = FC->getPredicate();
1516 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1517 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001518 SDOperand Op1 = getValue(I.getOperand(0));
1519 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001520 ISD::CondCode Condition, FOC, FPC;
1521 switch (predicate) {
1522 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1523 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1524 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1525 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1526 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1527 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1528 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1529 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1530 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1531 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1532 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1533 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1534 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1535 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1536 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1537 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1538 default:
1539 assert(!"Invalid FCmp predicate value");
1540 FOC = FPC = ISD::SETFALSE;
1541 break;
1542 }
1543 if (FiniteOnlyFPMath())
1544 Condition = FOC;
1545 else
1546 Condition = FPC;
1547 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001548}
1549
1550void SelectionDAGLowering::visitSelect(User &I) {
1551 SDOperand Cond = getValue(I.getOperand(0));
1552 SDOperand TrueVal = getValue(I.getOperand(1));
1553 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001554 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001555 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1556 TrueVal, FalseVal));
1557 } else {
1558 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1559 *(TrueVal.Val->op_end()-2),
1560 *(TrueVal.Val->op_end()-1)));
1561 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001562}
1563
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001564
1565void SelectionDAGLowering::visitTrunc(User &I) {
1566 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1567 SDOperand N = getValue(I.getOperand(0));
1568 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1569 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1570}
1571
1572void SelectionDAGLowering::visitZExt(User &I) {
1573 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1574 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1575 SDOperand N = getValue(I.getOperand(0));
1576 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1577 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1578}
1579
1580void SelectionDAGLowering::visitSExt(User &I) {
1581 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1582 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1583 SDOperand N = getValue(I.getOperand(0));
1584 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1585 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1586}
1587
1588void SelectionDAGLowering::visitFPTrunc(User &I) {
1589 // FPTrunc is never a no-op cast, no need to check
1590 SDOperand N = getValue(I.getOperand(0));
1591 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1592 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1593}
1594
1595void SelectionDAGLowering::visitFPExt(User &I){
1596 // FPTrunc is never a no-op cast, no need to check
1597 SDOperand N = getValue(I.getOperand(0));
1598 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1599 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1600}
1601
1602void SelectionDAGLowering::visitFPToUI(User &I) {
1603 // FPToUI is never a no-op cast, no need to check
1604 SDOperand N = getValue(I.getOperand(0));
1605 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1606 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1607}
1608
1609void SelectionDAGLowering::visitFPToSI(User &I) {
1610 // FPToSI is never a no-op cast, no need to check
1611 SDOperand N = getValue(I.getOperand(0));
1612 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1613 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1614}
1615
1616void SelectionDAGLowering::visitUIToFP(User &I) {
1617 // UIToFP is never a no-op cast, no need to check
1618 SDOperand N = getValue(I.getOperand(0));
1619 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1620 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1621}
1622
1623void SelectionDAGLowering::visitSIToFP(User &I){
1624 // UIToFP is never a no-op cast, no need to check
1625 SDOperand N = getValue(I.getOperand(0));
1626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1627 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1628}
1629
1630void SelectionDAGLowering::visitPtrToInt(User &I) {
1631 // What to do depends on the size of the integer and the size of the pointer.
1632 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001633 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001634 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001635 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001636 SDOperand Result;
1637 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1638 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1639 else
1640 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1641 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1642 setValue(&I, Result);
1643}
Chris Lattner7a60d912005-01-07 07:47:53 +00001644
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001645void SelectionDAGLowering::visitIntToPtr(User &I) {
1646 // What to do depends on the size of the integer and the size of the pointer.
1647 // We can either truncate, zero extend, or no-op, accordingly.
1648 SDOperand N = getValue(I.getOperand(0));
1649 MVT::ValueType SrcVT = N.getValueType();
1650 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1651 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1652 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1653 else
1654 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1655 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1656}
1657
1658void SelectionDAGLowering::visitBitCast(User &I) {
1659 SDOperand N = getValue(I.getOperand(0));
1660 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001661 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001662 // This is a cast to a vector from something else.
1663 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001664 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001665 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1666 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1667 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1668 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001669 return;
1670 }
1671 MVT::ValueType SrcVT = N.getValueType();
1672 if (SrcVT == MVT::Vector) {
1673 // This is a cast from a vctor to something else.
1674 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001675 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001676 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001677 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001678
1679 // BitCast assures us that source and destination are the same size so this
1680 // is either a BIT_CONVERT or a no-op.
1681 if (DestVT != N.getValueType())
1682 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1683 else
1684 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001685}
1686
Chris Lattner67271862006-03-29 00:11:43 +00001687void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001688 SDOperand InVec = getValue(I.getOperand(0));
1689 SDOperand InVal = getValue(I.getOperand(1));
1690 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1691 getValue(I.getOperand(2)));
1692
Chris Lattner29b23012006-03-19 01:17:20 +00001693 SDOperand Num = *(InVec.Val->op_end()-2);
1694 SDOperand Typ = *(InVec.Val->op_end()-1);
1695 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1696 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001697}
1698
Chris Lattner67271862006-03-29 00:11:43 +00001699void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001700 SDOperand InVec = getValue(I.getOperand(0));
1701 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1702 getValue(I.getOperand(1)));
1703 SDOperand Typ = *(InVec.Val->op_end()-1);
1704 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1705 TLI.getValueType(I.getType()), InVec, InIdx));
1706}
Chris Lattner32206f52006-03-18 01:44:44 +00001707
Chris Lattner098c01e2006-04-08 04:15:24 +00001708void SelectionDAGLowering::visitShuffleVector(User &I) {
1709 SDOperand V1 = getValue(I.getOperand(0));
1710 SDOperand V2 = getValue(I.getOperand(1));
1711 SDOperand Mask = getValue(I.getOperand(2));
1712
1713 SDOperand Num = *(V1.Val->op_end()-2);
1714 SDOperand Typ = *(V2.Val->op_end()-1);
1715 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1716 V1, V2, Mask, Num, Typ));
1717}
1718
1719
Chris Lattner7a60d912005-01-07 07:47:53 +00001720void SelectionDAGLowering::visitGetElementPtr(User &I) {
1721 SDOperand N = getValue(I.getOperand(0));
1722 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001723
1724 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1725 OI != E; ++OI) {
1726 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001727 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001728 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001729 if (Field) {
1730 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001731 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001732 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001733 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001734 }
1735 Ty = StTy->getElementType(Field);
1736 } else {
1737 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001738
Chris Lattner43535a12005-11-09 04:45:33 +00001739 // If this is a constant subscript, handle it quickly.
1740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001741 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001742 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001743 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001744 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1745 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001746 }
Chris Lattner43535a12005-11-09 04:45:33 +00001747
1748 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001749 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001750 SDOperand IdxN = getValue(Idx);
1751
1752 // If the index is smaller or larger than intptr_t, truncate or extend
1753 // it.
1754 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001755 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001756 } else if (IdxN.getValueType() > N.getValueType())
1757 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1758
1759 // If this is a multiply by a power of two, turn it into a shl
1760 // immediately. This is a very common case.
1761 if (isPowerOf2_64(ElementSize)) {
1762 unsigned Amt = Log2_64(ElementSize);
1763 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001764 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001765 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1766 continue;
1767 }
1768
1769 SDOperand Scale = getIntPtrConstant(ElementSize);
1770 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1771 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001772 }
1773 }
1774 setValue(&I, N);
1775}
1776
1777void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1778 // If this is a fixed sized alloca in the entry block of the function,
1779 // allocate it statically on the stack.
1780 if (FuncInfo.StaticAllocaMap.count(&I))
1781 return; // getValue will auto-populate this.
1782
1783 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001784 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001785 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00001786 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00001787 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001788
1789 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001790 MVT::ValueType IntPtr = TLI.getPointerTy();
1791 if (IntPtr < AllocSize.getValueType())
1792 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1793 else if (IntPtr > AllocSize.getValueType())
1794 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001795
Chris Lattnereccb73d2005-01-22 23:04:37 +00001796 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001797 getIntPtrConstant(TySize));
1798
1799 // Handle alignment. If the requested alignment is less than or equal to the
1800 // stack alignment, ignore it and round the size of the allocation up to the
1801 // stack alignment size. If the size is greater than the stack alignment, we
1802 // note this in the DYNAMIC_STACKALLOC node.
1803 unsigned StackAlign =
1804 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1805 if (Align <= StackAlign) {
1806 Align = 0;
1807 // Add SA-1 to the size.
1808 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1809 getIntPtrConstant(StackAlign-1));
1810 // Mask out the low bits for alignment purposes.
1811 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1812 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1813 }
1814
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001815 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001816 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1817 MVT::Other);
1818 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00001819 setValue(&I, DSA);
1820 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001821
1822 // Inform the Frame Information that we have just allocated a variable-sized
1823 // object.
1824 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1825}
1826
Chris Lattner7a60d912005-01-07 07:47:53 +00001827void SelectionDAGLowering::visitLoad(LoadInst &I) {
1828 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001829
Chris Lattner4d9651c2005-01-17 22:19:26 +00001830 SDOperand Root;
1831 if (I.isVolatile())
1832 Root = getRoot();
1833 else {
1834 // Do not serialize non-volatile loads against each other.
1835 Root = DAG.getRoot();
1836 }
Chris Lattner4024c002006-03-15 22:19:46 +00001837
Evan Chenge71fe34d2006-10-09 20:57:25 +00001838 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001839 Root, I.isVolatile()));
1840}
1841
1842SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001843 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001844 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001845 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001846 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001847 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001848 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1849 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001850 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001851 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001852 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001853
Chris Lattner4024c002006-03-15 22:19:46 +00001854 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001855 DAG.setRoot(L.getValue(1));
1856 else
1857 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001858
1859 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001860}
1861
1862
1863void SelectionDAGLowering::visitStore(StoreInst &I) {
1864 Value *SrcV = I.getOperand(0);
1865 SDOperand Src = getValue(SrcV);
1866 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001867 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001868 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001869}
1870
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001871/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1872/// access memory and has no other side effects at all.
1873static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1874#define GET_NO_MEMORY_INTRINSICS
1875#include "llvm/Intrinsics.gen"
1876#undef GET_NO_MEMORY_INTRINSICS
1877 return false;
1878}
1879
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001880// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1881// have any side-effects or if it only reads memory.
1882static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1883#define GET_SIDE_EFFECT_INFO
1884#include "llvm/Intrinsics.gen"
1885#undef GET_SIDE_EFFECT_INFO
1886 return false;
1887}
1888
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001889/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1890/// node.
1891void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1892 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001893 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001894 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001895
1896 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001897 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001898 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1899 if (OnlyLoad) {
1900 // We don't need to serialize loads against other loads.
1901 Ops.push_back(DAG.getRoot());
1902 } else {
1903 Ops.push_back(getRoot());
1904 }
1905 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001906
1907 // Add the intrinsic ID as an integer operand.
1908 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1909
1910 // Add all operands of the call to the operand list.
1911 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1912 SDOperand Op = getValue(I.getOperand(i));
1913
Reid Spencer09575ba2007-02-15 03:39:18 +00001914 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001915 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001916 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001917 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1918
1919 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1920 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1921 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1922 }
1923
1924 assert(TLI.isTypeLegal(Op.getValueType()) &&
1925 "Intrinsic uses a non-legal type?");
1926 Ops.push_back(Op);
1927 }
1928
1929 std::vector<MVT::ValueType> VTs;
1930 if (I.getType() != Type::VoidTy) {
1931 MVT::ValueType VT = TLI.getValueType(I.getType());
1932 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001933 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001934 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1935
1936 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1937 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1938 }
1939
1940 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1941 VTs.push_back(VT);
1942 }
1943 if (HasChain)
1944 VTs.push_back(MVT::Other);
1945
Chris Lattnerbd887772006-08-14 23:53:35 +00001946 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1947
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001948 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001949 SDOperand Result;
1950 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001951 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1952 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001953 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001954 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1955 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001956 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001957 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1958 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001959
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001960 if (HasChain) {
1961 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1962 if (OnlyLoad)
1963 PendingLoads.push_back(Chain);
1964 else
1965 DAG.setRoot(Chain);
1966 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001967 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001968 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001969 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1970 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1971 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1972 DAG.getValueType(EVT));
1973 }
1974 setValue(&I, Result);
1975 }
1976}
1977
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001978/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1979/// we want to emit this as a call to a named external function, return the name
1980/// otherwise lower it and return null.
1981const char *
1982SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1983 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001984 default:
1985 // By default, turn this into a target intrinsic node.
1986 visitTargetIntrinsic(I, Intrinsic);
1987 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001988 case Intrinsic::vastart: visitVAStart(I); return 0;
1989 case Intrinsic::vaend: visitVAEnd(I); return 0;
1990 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00001991 case Intrinsic::returnaddress:
1992 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1993 getValue(I.getOperand(1))));
1994 return 0;
1995 case Intrinsic::frameaddress:
1996 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1997 getValue(I.getOperand(1))));
1998 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001999 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002000 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002001 break;
2002 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002003 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002004 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002005 case Intrinsic::memcpy_i32:
2006 case Intrinsic::memcpy_i64:
2007 visitMemIntrinsic(I, ISD::MEMCPY);
2008 return 0;
2009 case Intrinsic::memset_i32:
2010 case Intrinsic::memset_i64:
2011 visitMemIntrinsic(I, ISD::MEMSET);
2012 return 0;
2013 case Intrinsic::memmove_i32:
2014 case Intrinsic::memmove_i64:
2015 visitMemIntrinsic(I, ISD::MEMMOVE);
2016 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002017
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002018 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002019 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002020 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002021 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002022 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002023
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002024 Ops[0] = getRoot();
2025 Ops[1] = getValue(SPI.getLineValue());
2026 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002027
Jim Laskeyc56315c2007-01-26 21:22:28 +00002028 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002029 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002030 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2031
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002032 Ops[3] = DAG.getString(CompileUnit->getFileName());
2033 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002034
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002035 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002036 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002037
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002038 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002039 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002040 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002041 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002042 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002043 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2044 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002045 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002046 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002047 }
2048
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002049 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002050 }
2051 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002052 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002053 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002054 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2055 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002056 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002057 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002058 }
2059
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002060 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002061 }
2062 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002063 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002064 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002065 if (MMI && FSI.getSubprogram() &&
2066 MMI->Verify(FSI.getSubprogram())) {
2067 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002068 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002069 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002070 }
2071
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002072 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002073 }
2074 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002075 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002076 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002077 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002078 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002079 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002080 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002081 }
2082
2083 return 0;
2084 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002085
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002086 case Intrinsic::eh_exception: {
2087 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2088
Jim Laskey504e9942007-02-22 15:38:06 +00002089 if (MMI) {
2090 // Add a label to mark the beginning of the landing pad. Deletion of the
2091 // landing pad can thus be detected via the MachineModuleInfo.
2092 unsigned LabelID = MMI->addLandingPad(CurMBB);
2093 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2094 DAG.getConstant(LabelID, MVT::i32)));
2095
2096 // Mark exception register as live in.
2097 unsigned Reg = TLI.getExceptionAddressRegister();
2098 if (Reg) CurMBB->addLiveIn(Reg);
2099
2100 // Insert the EXCEPTIONADDR instruction.
2101 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2102 SDOperand Ops[1];
2103 Ops[0] = DAG.getRoot();
2104 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2105 setValue(&I, Op);
2106 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002107 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002108 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002109 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002110 return 0;
2111 }
2112
Jim Laskeyd5453d72007-03-01 20:24:30 +00002113 case Intrinsic::eh_selector:
2114 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002115 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2116
Jim Laskey504e9942007-02-22 15:38:06 +00002117 if (MMI) {
2118 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002119 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2120 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2121 isa<Function>(CE->getOperand(0)) &&
2122 "Personality should be a function");
2123 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002124 if (Intrinsic == Intrinsic::eh_filter)
2125 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002126
Jim Laskey504e9942007-02-22 15:38:06 +00002127 // Gather all the type infos for this landing pad and pass them along to
2128 // MachineModuleInfo.
2129 std::vector<GlobalVariable *> TyInfo;
2130 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002131 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2132 if (CE && CE->getOpcode() == Instruction::BitCast &&
2133 isa<GlobalVariable>(CE->getOperand(0))) {
2134 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2135 } else {
2136 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2137 assert(CI && CI->getZExtValue() == 0 &&
2138 "TypeInfo must be a global variable typeinfo or NULL");
2139 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002140 }
Jim Laskey504e9942007-02-22 15:38:06 +00002141 }
2142 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2143
2144 // Mark exception selector register as live in.
2145 unsigned Reg = TLI.getExceptionSelectorRegister();
2146 if (Reg) CurMBB->addLiveIn(Reg);
2147
2148 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002149 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002150 SDOperand Ops[2];
2151 Ops[0] = getValue(I.getOperand(1));
2152 Ops[1] = getRoot();
2153 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2154 setValue(&I, Op);
2155 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002156 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002157 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002158 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002159
2160 return 0;
2161 }
2162
2163 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002164 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002165
Jim Laskey504e9942007-02-22 15:38:06 +00002166 if (MMI) {
2167 // Find the type id for the given typeinfo.
2168 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002169 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2170 if (CE && CE->getOpcode() == Instruction::BitCast &&
2171 isa<GlobalVariable>(CE->getOperand(0))) {
2172 GV = cast<GlobalVariable>(CE->getOperand(0));
2173 } else {
2174 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2175 assert(CI && CI->getZExtValue() == 0 &&
2176 "TypeInfo must be a global variable typeinfo or NULL");
2177 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002178 }
2179
2180 unsigned TypeID = MMI->getTypeIDFor(GV);
2181 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002182 } else {
2183 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002184 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002185
2186 return 0;
2187 }
2188
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002189 case Intrinsic::sqrt_f32:
2190 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002191 setValue(&I, DAG.getNode(ISD::FSQRT,
2192 getValue(I.getOperand(1)).getValueType(),
2193 getValue(I.getOperand(1))));
2194 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002195 case Intrinsic::powi_f32:
2196 case Intrinsic::powi_f64:
2197 setValue(&I, DAG.getNode(ISD::FPOWI,
2198 getValue(I.getOperand(1)).getValueType(),
2199 getValue(I.getOperand(1)),
2200 getValue(I.getOperand(2))));
2201 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002202 case Intrinsic::pcmarker: {
2203 SDOperand Tmp = getValue(I.getOperand(1));
2204 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2205 return 0;
2206 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002207 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002208 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002209 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2210 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2211 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002212 setValue(&I, Tmp);
2213 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002214 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002215 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002216 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002217 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002218 case Intrinsic::bswap_i64:
2219 setValue(&I, DAG.getNode(ISD::BSWAP,
2220 getValue(I.getOperand(1)).getValueType(),
2221 getValue(I.getOperand(1))));
2222 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002223 case Intrinsic::cttz_i8:
2224 case Intrinsic::cttz_i16:
2225 case Intrinsic::cttz_i32:
2226 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002227 setValue(&I, DAG.getNode(ISD::CTTZ,
2228 getValue(I.getOperand(1)).getValueType(),
2229 getValue(I.getOperand(1))));
2230 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002231 case Intrinsic::ctlz_i8:
2232 case Intrinsic::ctlz_i16:
2233 case Intrinsic::ctlz_i32:
2234 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002235 setValue(&I, DAG.getNode(ISD::CTLZ,
2236 getValue(I.getOperand(1)).getValueType(),
2237 getValue(I.getOperand(1))));
2238 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002239 case Intrinsic::ctpop_i8:
2240 case Intrinsic::ctpop_i16:
2241 case Intrinsic::ctpop_i32:
2242 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002243 setValue(&I, DAG.getNode(ISD::CTPOP,
2244 getValue(I.getOperand(1)).getValueType(),
2245 getValue(I.getOperand(1))));
2246 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002247 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002248 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002249 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2250 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002251 setValue(&I, Tmp);
2252 DAG.setRoot(Tmp.getValue(1));
2253 return 0;
2254 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002255 case Intrinsic::stackrestore: {
2256 SDOperand Tmp = getValue(I.getOperand(1));
2257 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002258 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002259 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002260 case Intrinsic::prefetch:
2261 // FIXME: Currently discarding prefetches.
2262 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002263 }
2264}
2265
2266
Jim Laskey31fef782007-02-23 21:45:01 +00002267void SelectionDAGLowering::LowerCallTo(Instruction &I,
2268 const Type *CalledValueTy,
2269 unsigned CallingConv,
2270 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002271 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002272 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002273 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2274
2275 TargetLowering::ArgListTy Args;
2276 TargetLowering::ArgListEntry Entry;
2277 Args.reserve(I.getNumOperands());
2278 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2279 Value *Arg = I.getOperand(i);
2280 SDOperand ArgNode = getValue(Arg);
2281 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00002282 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2283 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002284 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2285 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2286 Args.push_back(Entry);
2287 }
2288
2289 std::pair<SDOperand,SDOperand> Result =
2290 TLI.LowerCallTo(getRoot(), I.getType(),
2291 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002292 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002293 Callee, Args, DAG);
2294 if (I.getType() != Type::VoidTy)
2295 setValue(&I, Result.first);
2296 DAG.setRoot(Result.second);
2297}
2298
2299
Chris Lattner7a60d912005-01-07 07:47:53 +00002300void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002301 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002302 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002303 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002304 if (unsigned IID = F->getIntrinsicID()) {
2305 RenameFn = visitIntrinsicCall(I, IID);
2306 if (!RenameFn)
2307 return;
2308 } else { // Not an LLVM intrinsic.
2309 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002310 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2311 if (I.getNumOperands() == 3 && // Basic sanity checks.
2312 I.getOperand(1)->getType()->isFloatingPoint() &&
2313 I.getType() == I.getOperand(1)->getType() &&
2314 I.getType() == I.getOperand(2)->getType()) {
2315 SDOperand LHS = getValue(I.getOperand(1));
2316 SDOperand RHS = getValue(I.getOperand(2));
2317 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2318 LHS, RHS));
2319 return;
2320 }
2321 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002322 if (I.getNumOperands() == 2 && // Basic sanity checks.
2323 I.getOperand(1)->getType()->isFloatingPoint() &&
2324 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002325 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002326 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2327 return;
2328 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002329 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002330 if (I.getNumOperands() == 2 && // Basic sanity checks.
2331 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002332 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002333 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002334 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2335 return;
2336 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002337 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002338 if (I.getNumOperands() == 2 && // Basic sanity checks.
2339 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002340 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002341 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002342 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2343 return;
2344 }
2345 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002346 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002347 } else if (isa<InlineAsm>(I.getOperand(0))) {
2348 visitInlineAsm(I);
2349 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002350 }
Misha Brukman835702a2005-04-21 22:36:52 +00002351
Chris Lattner18d2b342005-01-08 22:48:57 +00002352 SDOperand Callee;
2353 if (!RenameFn)
2354 Callee = getValue(I.getOperand(0));
2355 else
2356 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002357
Jim Laskey31fef782007-02-23 21:45:01 +00002358 LowerCallTo(I, I.getCalledValue()->getType(),
2359 I.getCallingConv(),
2360 I.isTailCall(),
2361 Callee,
2362 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002363}
2364
Jim Laskey504e9942007-02-22 15:38:06 +00002365
Chris Lattner6f87d182006-02-22 22:37:12 +00002366SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002367 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002368 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2369 Chain = Val.getValue(1);
2370 Flag = Val.getValue(2);
2371
2372 // If the result was expanded, copy from the top part.
2373 if (Regs.size() > 1) {
2374 assert(Regs.size() == 2 &&
2375 "Cannot expand to more than 2 elts yet!");
2376 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002377 Chain = Hi.getValue(1);
2378 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002379 if (DAG.getTargetLoweringInfo().isLittleEndian())
2380 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2381 else
2382 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002383 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002384
Chris Lattner705948d2006-06-08 18:22:48 +00002385 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002386 // appropriate type.
2387 if (RegVT == ValueVT)
2388 return Val;
2389
Chris Lattner77f04792007-03-25 05:00:54 +00002390 if (MVT::isVector(RegVT)) {
2391 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2392 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2393 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2394 MVT::i32),
2395 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2396 }
2397
Chris Lattner705948d2006-06-08 18:22:48 +00002398 if (MVT::isInteger(RegVT)) {
2399 if (ValueVT < RegVT)
2400 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2401 else
2402 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002403 }
Chris Lattner77f04792007-03-25 05:00:54 +00002404
2405 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2406 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002407}
2408
Chris Lattner571d9642006-02-23 19:21:04 +00002409/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2410/// specified value into the registers specified by this object. This uses
2411/// Chain/Flag as the input and updates them for the output Chain/Flag.
2412void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002413 SDOperand &Chain, SDOperand &Flag,
2414 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002415 if (Regs.size() == 1) {
2416 // If there is a single register and the types differ, this must be
2417 // a promotion.
2418 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002419 if (MVT::isVector(RegVT)) {
2420 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2421 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2422 } else if (MVT::isInteger(RegVT)) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002423 if (RegVT < ValueVT)
2424 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2425 else
2426 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2427 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002428 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2429 }
2430 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2431 Flag = Chain.getValue(1);
2432 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002433 std::vector<unsigned> R(Regs);
2434 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2435 std::reverse(R.begin(), R.end());
2436
2437 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002438 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002439 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002440 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002441 Flag = Chain.getValue(1);
2442 }
2443 }
2444}
Chris Lattner6f87d182006-02-22 22:37:12 +00002445
Chris Lattner571d9642006-02-23 19:21:04 +00002446/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2447/// operand list. This adds the code marker and includes the number of
2448/// values added into it.
2449void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002450 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002451 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2452 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2453 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2454}
Chris Lattner6f87d182006-02-22 22:37:12 +00002455
2456/// isAllocatableRegister - If the specified register is safe to allocate,
2457/// i.e. it isn't a stack pointer or some other special register, return the
2458/// register class for the register. Otherwise, return null.
2459static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002460isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2461 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002462 MVT::ValueType FoundVT = MVT::Other;
2463 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002464 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2465 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002466 MVT::ValueType ThisVT = MVT::Other;
2467
Chris Lattnerb1124f32006-02-22 23:09:03 +00002468 const TargetRegisterClass *RC = *RCI;
2469 // If none of the the value types for this register class are valid, we
2470 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002471 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2472 I != E; ++I) {
2473 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002474 // If we have already found this register in a different register class,
2475 // choose the one with the largest VT specified. For example, on
2476 // PowerPC, we favor f64 register classes over f32.
2477 if (FoundVT == MVT::Other ||
2478 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2479 ThisVT = *I;
2480 break;
2481 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002482 }
2483 }
2484
Chris Lattnerbec582f2006-04-02 00:24:45 +00002485 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002486
Chris Lattner6f87d182006-02-22 22:37:12 +00002487 // NOTE: This isn't ideal. In particular, this might allocate the
2488 // frame pointer in functions that need it (due to them not being taken
2489 // out of allocation, because a variable sized allocation hasn't been seen
2490 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002491 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2492 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002493 if (*I == Reg) {
2494 // We found a matching register class. Keep looking at others in case
2495 // we find one with larger registers that this physreg is also in.
2496 FoundRC = RC;
2497 FoundVT = ThisVT;
2498 break;
2499 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002500 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002501 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002502}
2503
2504RegsForValue SelectionDAGLowering::
2505GetRegistersForValue(const std::string &ConstrCode,
2506 MVT::ValueType VT, bool isOutReg, bool isInReg,
2507 std::set<unsigned> &OutputRegs,
2508 std::set<unsigned> &InputRegs) {
2509 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2510 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2511 std::vector<unsigned> Regs;
2512
2513 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2514 MVT::ValueType RegVT;
2515 MVT::ValueType ValueVT = VT;
2516
Chris Lattner55402d42006-11-02 01:41:49 +00002517 // If this is a constraint for a specific physical register, like {r17},
2518 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002519 if (PhysReg.first) {
2520 if (VT == MVT::Other)
2521 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002522
2523 // Get the actual register value type. This is important, because the user
2524 // may have asked for (e.g.) the AX register in i32 type. We need to
2525 // remember that AX is actually i16 to get the right extension.
2526 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002527
2528 // This is a explicit reference to a physical register.
2529 Regs.push_back(PhysReg.first);
2530
2531 // If this is an expanded reference, add the rest of the regs to Regs.
2532 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002533 TargetRegisterClass::iterator I = PhysReg.second->begin();
2534 TargetRegisterClass::iterator E = PhysReg.second->end();
2535 for (; *I != PhysReg.first; ++I)
2536 assert(I != E && "Didn't find reg!");
2537
2538 // Already added the first reg.
2539 --NumRegs; ++I;
2540 for (; NumRegs; --NumRegs, ++I) {
2541 assert(I != E && "Ran out of registers to allocate!");
2542 Regs.push_back(*I);
2543 }
2544 }
2545 return RegsForValue(Regs, RegVT, ValueVT);
2546 }
2547
Chris Lattner55402d42006-11-02 01:41:49 +00002548 // Otherwise, if this was a reference to an LLVM register class, create vregs
2549 // for this reference.
2550 std::vector<unsigned> RegClassRegs;
2551 if (PhysReg.second) {
2552 // If this is an early clobber or tied register, our regalloc doesn't know
2553 // how to maintain the constraint. If it isn't, go ahead and create vreg
2554 // and let the regalloc do the right thing.
2555 if (!isOutReg || !isInReg) {
2556 if (VT == MVT::Other)
2557 ValueVT = *PhysReg.second->vt_begin();
2558 RegVT = *PhysReg.second->vt_begin();
2559
2560 // Create the appropriate number of virtual registers.
2561 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2562 for (; NumRegs; --NumRegs)
2563 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2564
2565 return RegsForValue(Regs, RegVT, ValueVT);
2566 }
2567
2568 // Otherwise, we can't allocate it. Let the code below figure out how to
2569 // maintain these constraints.
2570 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2571
2572 } else {
2573 // This is a reference to a register class that doesn't directly correspond
2574 // to an LLVM register class. Allocate NumRegs consecutive, available,
2575 // registers from the class.
2576 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2577 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002578
2579 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2580 MachineFunction &MF = *CurMBB->getParent();
2581 unsigned NumAllocated = 0;
2582 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2583 unsigned Reg = RegClassRegs[i];
2584 // See if this register is available.
2585 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2586 (isInReg && InputRegs.count(Reg))) { // Already used.
2587 // Make sure we find consecutive registers.
2588 NumAllocated = 0;
2589 continue;
2590 }
2591
2592 // Check to see if this register is allocatable (i.e. don't give out the
2593 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002594 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002595 if (!RC) {
2596 // Make sure we find consecutive registers.
2597 NumAllocated = 0;
2598 continue;
2599 }
2600
2601 // Okay, this register is good, we can use it.
2602 ++NumAllocated;
2603
2604 // If we allocated enough consecutive
2605 if (NumAllocated == NumRegs) {
2606 unsigned RegStart = (i-NumAllocated)+1;
2607 unsigned RegEnd = i+1;
2608 // Mark all of the allocated registers used.
2609 for (unsigned i = RegStart; i != RegEnd; ++i) {
2610 unsigned Reg = RegClassRegs[i];
2611 Regs.push_back(Reg);
2612 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2613 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2614 }
2615
2616 return RegsForValue(Regs, *RC->vt_begin(), VT);
2617 }
2618 }
2619
2620 // Otherwise, we couldn't allocate enough registers for this.
2621 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002622}
2623
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002624/// getConstraintGenerality - Return an integer indicating how general CT is.
2625static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2626 switch (CT) {
2627 default: assert(0 && "Unknown constraint type!");
2628 case TargetLowering::C_Other:
2629 case TargetLowering::C_Unknown:
2630 return 0;
2631 case TargetLowering::C_Register:
2632 return 1;
2633 case TargetLowering::C_RegisterClass:
2634 return 2;
2635 case TargetLowering::C_Memory:
2636 return 3;
2637 }
2638}
2639
2640static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2641 const TargetLowering &TLI) {
2642 assert(!C.empty() && "Must have at least one constraint");
2643 if (C.size() == 1) return C[0];
2644
2645 std::string *Current = &C[0];
2646 // If we have multiple constraints, try to pick the most general one ahead
2647 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00002648 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002649 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002650 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002651 if (getConstraintGenerality(ThisFlavor) >
2652 getConstraintGenerality(Flavor)) {
2653 // This constraint letter is more general than the previous one,
2654 // use it.
2655 Flavor = ThisFlavor;
2656 Current = &C[j];
2657 }
2658 }
2659 return *Current;
2660}
2661
Chris Lattner6f87d182006-02-22 22:37:12 +00002662
Chris Lattner476e67b2006-01-26 22:24:51 +00002663/// visitInlineAsm - Handle a call to an InlineAsm object.
2664///
2665void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2666 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2667
2668 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2669 MVT::Other);
2670
Chris Lattner3a5ed552006-02-01 01:28:23 +00002671 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002672 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002673
2674 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2675 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2676 /// if it is a def of that register.
2677 std::vector<SDOperand> AsmNodeOperands;
2678 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2679 AsmNodeOperands.push_back(AsmStr);
2680
2681 SDOperand Chain = getRoot();
2682 SDOperand Flag;
2683
Chris Lattner1558fc62006-02-01 18:59:47 +00002684 // We fully assign registers here at isel time. This is not optimal, but
2685 // should work. For register classes that correspond to LLVM classes, we
2686 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2687 // over the constraints, collecting fixed registers that we know we can't use.
2688 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002689 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002690 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002691 std::string ConstraintCode =
2692 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002693
Chris Lattner7ad77df2006-02-22 00:56:39 +00002694 MVT::ValueType OpVT;
2695
2696 // Compute the value type for each operand and add it to ConstraintVTs.
2697 switch (Constraints[i].Type) {
2698 case InlineAsm::isOutput:
2699 if (!Constraints[i].isIndirectOutput) {
2700 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2701 OpVT = TLI.getValueType(I.getType());
2702 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002703 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002704 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2705 OpNum++; // Consumes a call operand.
2706 }
2707 break;
2708 case InlineAsm::isInput:
2709 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2710 OpNum++; // Consumes a call operand.
2711 break;
2712 case InlineAsm::isClobber:
2713 OpVT = MVT::Other;
2714 break;
2715 }
2716
2717 ConstraintVTs.push_back(OpVT);
2718
Chris Lattner6f87d182006-02-22 22:37:12 +00002719 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2720 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002721
Chris Lattner6f87d182006-02-22 22:37:12 +00002722 // Build a list of regs that this operand uses. This always has a single
2723 // element for promoted/expanded operands.
2724 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2725 false, false,
2726 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002727
2728 switch (Constraints[i].Type) {
2729 case InlineAsm::isOutput:
2730 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002731 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002732 // If this is an early-clobber output, it cannot be assigned to the same
2733 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002734 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002735 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002736 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002737 case InlineAsm::isInput:
2738 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002739 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002740 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002741 case InlineAsm::isClobber:
2742 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002743 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2744 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002745 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002746 }
2747 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002748
Chris Lattner5c79f982006-02-21 23:12:12 +00002749 // Loop over all of the inputs, copying the operand values into the
2750 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002751 RegsForValue RetValRegs;
2752 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002753 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002754
Chris Lattner2e56e892006-01-31 02:03:41 +00002755 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002756 std::string ConstraintCode =
2757 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002758
Chris Lattner3a5ed552006-02-01 01:28:23 +00002759 switch (Constraints[i].Type) {
2760 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002761 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2762 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002763 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00002764
2765 if (CTy == TargetLowering::C_Memory) {
2766 // Memory output.
2767 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2768
2769 // Check that the operand (the address to store to) isn't a float.
2770 if (!MVT::isInteger(InOperandVal.getValueType()))
2771 assert(0 && "MATCH FAIL!");
2772
2773 if (!Constraints[i].isIndirectOutput)
2774 assert(0 && "MATCH FAIL!");
2775
2776 OpNum++; // Consumes a call operand.
2777
2778 // Extend/truncate to the right pointer type if needed.
2779 MVT::ValueType PtrType = TLI.getPointerTy();
2780 if (InOperandVal.getValueType() < PtrType)
2781 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2782 else if (InOperandVal.getValueType() > PtrType)
2783 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2784
2785 // Add information to the INLINEASM node to know about this output.
2786 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2787 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2788 AsmNodeOperands.push_back(InOperandVal);
2789 break;
2790 }
2791
2792 // Otherwise, this is a register output.
2793 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2794
Chris Lattner6f87d182006-02-22 22:37:12 +00002795 // If this is an early-clobber output, or if there is an input
2796 // constraint that matches this, we need to reserve the input register
2797 // so no other inputs allocate to it.
2798 bool UsesInputRegister = false;
2799 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2800 UsesInputRegister = true;
2801
2802 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002803 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002804 RegsForValue Regs =
2805 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2806 true, UsesInputRegister,
2807 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002808 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002809 cerr << "Couldn't allocate output reg for contraint '"
2810 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002811 exit(1);
2812 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002813
Chris Lattner3a5ed552006-02-01 01:28:23 +00002814 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002815 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002816 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002817 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002818 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002819 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002820 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2821 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002822 OpNum++; // Consumes a call operand.
2823 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002824
2825 // Add information to the INLINEASM node to know that this register is
2826 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002827 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002828 break;
2829 }
2830 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002831 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002832 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002833
Chris Lattner7f5880b2006-02-02 00:25:23 +00002834 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2835 // If this is required to match an output register we have already set,
2836 // just use its register.
2837 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002838
Chris Lattner571d9642006-02-23 19:21:04 +00002839 // Scan until we find the definition we already emitted of this operand.
2840 // When we find it, create a RegsForValue operand.
2841 unsigned CurOp = 2; // The first operand.
2842 for (; OperandNo; --OperandNo) {
2843 // Advance to the next operand.
2844 unsigned NumOps =
2845 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002846 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2847 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002848 "Skipped past definitions?");
2849 CurOp += (NumOps>>3)+1;
2850 }
2851
2852 unsigned NumOps =
2853 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00002854 if ((NumOps & 7) == 2 /*REGDEF*/) {
2855 // Add NumOps>>3 registers to MatchedRegs.
2856 RegsForValue MatchedRegs;
2857 MatchedRegs.ValueVT = InOperandVal.getValueType();
2858 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2859 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2860 unsigned Reg =
2861 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2862 MatchedRegs.Regs.push_back(Reg);
2863 }
Chris Lattner571d9642006-02-23 19:21:04 +00002864
Chris Lattnere3eeb242007-02-01 01:21:12 +00002865 // Use the produced MatchedRegs object to
2866 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2867 TLI.getPointerTy());
2868 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2869 break;
2870 } else {
2871 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2872 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00002873 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00002874 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002875
2876 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2877 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002878 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00002879
2880 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002881 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2882 ConstraintCode[0], DAG);
2883 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002884 cerr << "Invalid operand for inline asm constraint '"
2885 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00002886 exit(1);
2887 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002888
2889 // Add information to the INLINEASM node to know about this input.
2890 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2891 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2892 AsmNodeOperands.push_back(InOperandVal);
2893 break;
2894 } else if (CTy == TargetLowering::C_Memory) {
2895 // Memory input.
2896
Chris Lattnerce8aba02007-03-08 22:29:47 +00002897 // If the operand is a float, spill to a constant pool entry to get its
2898 // address.
2899 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
2900 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
2901
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00002902 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00002903 cerr << "Match failed, cannot handle this yet!\n";
2904 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00002905 exit(1);
2906 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002907
2908 // Extend/truncate to the right pointer type if needed.
2909 MVT::ValueType PtrType = TLI.getPointerTy();
2910 if (InOperandVal.getValueType() < PtrType)
2911 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2912 else if (InOperandVal.getValueType() > PtrType)
2913 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2914
2915 // Add information to the INLINEASM node to know about this input.
2916 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2917 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2918 AsmNodeOperands.push_back(InOperandVal);
2919 break;
2920 }
2921
2922 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2923
2924 // Copy the input into the appropriate registers.
2925 RegsForValue InRegs =
2926 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2927 false, true, OutputRegs, InputRegs);
2928 // FIXME: should be match fail.
2929 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2930
Evan Chengef9e07d2006-06-15 08:11:54 +00002931 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002932
2933 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002934 break;
2935 }
Chris Lattner571d9642006-02-23 19:21:04 +00002936 case InlineAsm::isClobber: {
2937 RegsForValue ClobberedRegs =
2938 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2939 OutputRegs, InputRegs);
2940 // Add the clobbered value to the operand list, so that the register
2941 // allocator is aware that the physreg got clobbered.
2942 if (!ClobberedRegs.Regs.empty())
2943 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002944 break;
2945 }
Chris Lattner571d9642006-02-23 19:21:04 +00002946 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002947 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002948
2949 // Finish up input operands.
2950 AsmNodeOperands[0] = Chain;
2951 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2952
Chris Lattnerbd887772006-08-14 23:53:35 +00002953 Chain = DAG.getNode(ISD::INLINEASM,
2954 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002955 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002956 Flag = Chain.getValue(1);
2957
Chris Lattner2e56e892006-01-31 02:03:41 +00002958 // If this asm returns a register value, copy the result from that register
2959 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002960 if (!RetValRegs.Regs.empty())
2961 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002962
Chris Lattner2e56e892006-01-31 02:03:41 +00002963 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2964
2965 // Process indirect outputs, first output all of the flagged copies out of
2966 // physregs.
2967 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002968 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002969 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002970 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2971 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002972 }
2973
2974 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002975 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002976 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002977 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002978 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002979 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002980 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002981 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2982 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002983 DAG.setRoot(Chain);
2984}
2985
2986
Chris Lattner7a60d912005-01-07 07:47:53 +00002987void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2988 SDOperand Src = getValue(I.getOperand(0));
2989
2990 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002991
2992 if (IntPtr < Src.getValueType())
2993 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2994 else if (IntPtr > Src.getValueType())
2995 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002996
2997 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002998 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002999 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3000 Src, getIntPtrConstant(ElementSize));
3001
Reid Spencere63b6512006-12-31 05:55:36 +00003002 TargetLowering::ArgListTy Args;
3003 TargetLowering::ArgListEntry Entry;
3004 Entry.Node = Src;
3005 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003006 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003007
3008 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003009 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003010 DAG.getExternalSymbol("malloc", IntPtr),
3011 Args, DAG);
3012 setValue(&I, Result.first); // Pointers always fit in registers
3013 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003014}
3015
3016void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003017 TargetLowering::ArgListTy Args;
3018 TargetLowering::ArgListEntry Entry;
3019 Entry.Node = getValue(I.getOperand(0));
3020 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003021 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003022 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003023 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003024 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003025 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3026 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003027}
3028
Chris Lattner13d7c252005-08-26 20:54:47 +00003029// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3030// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3031// instructions are special in various ways, which require special support to
3032// insert. The specified MachineInstr is created but not inserted into any
3033// basic blocks, and the scheduler passes ownership of it to this method.
3034MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3035 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003036 cerr << "If a target marks an instruction with "
3037 << "'usesCustomDAGSchedInserter', it must implement "
3038 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003039 abort();
3040 return 0;
3041}
3042
Chris Lattner58cfd792005-01-09 00:00:49 +00003043void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003044 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3045 getValue(I.getOperand(1)),
3046 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003047}
3048
3049void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003050 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3051 getValue(I.getOperand(0)),
3052 DAG.getSrcValue(I.getOperand(0)));
3053 setValue(&I, V);
3054 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003055}
3056
3057void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003058 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3059 getValue(I.getOperand(1)),
3060 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003061}
3062
3063void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003064 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3065 getValue(I.getOperand(1)),
3066 getValue(I.getOperand(2)),
3067 DAG.getSrcValue(I.getOperand(1)),
3068 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003069}
3070
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003071/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3072/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3073static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3074 unsigned &i, SelectionDAG &DAG,
3075 TargetLowering &TLI) {
3076 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3077 return SDOperand(Arg, i++);
3078
3079 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3080 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3081 if (NumVals == 1) {
3082 return DAG.getNode(ISD::BIT_CONVERT, VT,
3083 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3084 } else if (NumVals == 2) {
3085 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3086 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3087 if (!TLI.isLittleEndian())
3088 std::swap(Lo, Hi);
3089 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3090 } else {
3091 // Value scalarized into many values. Unimp for now.
3092 assert(0 && "Cannot expand i64 -> i16 yet!");
3093 }
3094 return SDOperand();
3095}
3096
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003097/// TargetLowering::LowerArguments - This is the default LowerArguments
3098/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003099/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3100/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003101std::vector<SDOperand>
3102TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003103 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003104 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3105 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003106 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003107 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3108 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3109
3110 // Add one result value for each formal argument.
3111 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003112 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003113 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3114 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003115 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003116 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003117 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003118 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003119
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003120 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3121 // that is zero extended!
3122 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003123 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003124 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003125 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003126 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003127 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003128 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003129 Flags |= ISD::ParamFlags::StructReturn;
3130 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003131
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003132 switch (getTypeAction(VT)) {
3133 default: assert(0 && "Unknown type action!");
3134 case Legal:
3135 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003136 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003137 break;
3138 case Promote:
3139 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003140 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003141 break;
3142 case Expand:
3143 if (VT != MVT::Vector) {
3144 // If this is a large integer, it needs to be broken up into small
3145 // integers. Figure out what the destination type is and how many small
3146 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003147 MVT::ValueType NVT = getTypeToExpandTo(VT);
3148 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003149 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003150 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003151 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003152 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003153 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3154 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003155 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3156 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003157 } else {
3158 // Otherwise, this is a vector type. We only support legal vectors
3159 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003160 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3161 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003162
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003163 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003164 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003165 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3166 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3167 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003168 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003169 } else {
3170 assert(0 && "Don't support illegal by-val vector arguments yet!");
3171 }
3172 }
3173 break;
3174 }
3175 }
Evan Cheng9618df12006-04-25 23:03:35 +00003176
Chris Lattner3d826992006-05-16 06:45:34 +00003177 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003178
3179 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003180 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3181 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003182 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003183
3184 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003185
3186 // Set up the return result vector.
3187 Ops.clear();
3188 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003189 unsigned Idx = 1;
3190 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3191 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003192 MVT::ValueType VT = getValueType(I->getType());
3193
3194 switch (getTypeAction(VT)) {
3195 default: assert(0 && "Unknown type action!");
3196 case Legal:
3197 Ops.push_back(SDOperand(Result, i++));
3198 break;
3199 case Promote: {
3200 SDOperand Op(Result, i++);
3201 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00003202 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3203 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3204 DAG.getValueType(VT));
3205 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3206 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3207 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003208 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3209 } else {
3210 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3211 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3212 }
3213 Ops.push_back(Op);
3214 break;
3215 }
3216 case Expand:
3217 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003218 // If this is a large integer or a floating point node that needs to be
3219 // expanded, it needs to be reassembled from small integers. Figure out
3220 // what the source elt type is and how many small integers it is.
3221 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003222 } else {
3223 // Otherwise, this is a vector type. We only support legal vectors
3224 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003225 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003226 unsigned NumElems = PTy->getNumElements();
3227 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003228
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003229 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003230 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003231 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003232 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003233 SDOperand N = SDOperand(Result, i++);
3234 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003235 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3236 DAG.getConstant(NumElems, MVT::i32),
3237 DAG.getValueType(getValueType(EltTy)));
3238 Ops.push_back(N);
3239 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003240 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003241 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003242 }
3243 }
3244 break;
3245 }
3246 }
3247 return Ops;
3248}
3249
Chris Lattneraaa23d92006-05-16 22:53:20 +00003250
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003251/// ExpandScalarCallArgs - Recursively expand call argument node by
3252/// bit_converting it or extract a pair of elements from the larger node.
3253static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003254 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003255 SmallVector<SDOperand, 32> &Ops,
3256 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003257 TargetLowering &TLI,
3258 bool isFirst = true) {
3259
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003260 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003261 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003262 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003263 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3264 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003265 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003266 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003267 return;
3268 }
3269
3270 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3271 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3272 if (NumVals == 1) {
3273 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003274 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003275 } else if (NumVals == 2) {
3276 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3277 DAG.getConstant(0, TLI.getPointerTy()));
3278 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3279 DAG.getConstant(1, TLI.getPointerTy()));
3280 if (!TLI.isLittleEndian())
3281 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003282 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3283 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003284 } else {
3285 // Value scalarized into many values. Unimp for now.
3286 assert(0 && "Cannot expand i64 -> i16 yet!");
3287 }
3288}
3289
Chris Lattneraaa23d92006-05-16 22:53:20 +00003290/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3291/// implementation, which just inserts an ISD::CALL node, which is later custom
3292/// lowered by the target to something concrete. FIXME: When all targets are
3293/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3294std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003295TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3296 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003297 unsigned CallingConv, bool isTailCall,
3298 SDOperand Callee,
3299 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003300 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003301 Ops.push_back(Chain); // Op#0 - Chain
3302 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3303 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3304 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3305 Ops.push_back(Callee);
3306
3307 // Handle all of the outgoing arguments.
3308 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003309 MVT::ValueType VT = getValueType(Args[i].Ty);
3310 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003311 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003312 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003313 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003314
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003315 if (Args[i].isSExt)
3316 Flags |= ISD::ParamFlags::SExt;
3317 if (Args[i].isZExt)
3318 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003319 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003320 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003321 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003322 Flags |= ISD::ParamFlags::StructReturn;
3323 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003324
Chris Lattneraaa23d92006-05-16 22:53:20 +00003325 switch (getTypeAction(VT)) {
3326 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003327 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003328 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003329 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003330 break;
3331 case Promote:
3332 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003333 unsigned ExtOp;
3334 if (Args[i].isSExt)
3335 ExtOp = ISD::SIGN_EXTEND;
3336 else if (Args[i].isZExt)
3337 ExtOp = ISD::ZERO_EXTEND;
3338 else
3339 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003340 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3341 } else {
3342 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3343 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3344 }
3345 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003346 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003347 break;
3348 case Expand:
3349 if (VT != MVT::Vector) {
3350 // If this is a large integer, it needs to be broken down into small
3351 // integers. Figure out what the source elt type is and how many small
3352 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003353 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003354 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003355 // Otherwise, this is a vector type. We only support legal vectors
3356 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003357 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003358 unsigned NumElems = PTy->getNumElements();
3359 const Type *EltTy = PTy->getElementType();
3360
3361 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003362 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003363 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003364 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003365 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003366 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3367 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003368 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003369 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003370 assert(0 && "Don't support illegal by-val vector call args yet!");
3371 abort();
3372 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003373 }
3374 break;
3375 }
3376 }
3377
3378 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003379 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003380
3381 if (RetTy != Type::VoidTy) {
3382 MVT::ValueType VT = getValueType(RetTy);
3383 switch (getTypeAction(VT)) {
3384 default: assert(0 && "Unknown type action!");
3385 case Legal:
3386 RetTys.push_back(VT);
3387 break;
3388 case Promote:
3389 RetTys.push_back(getTypeToTransformTo(VT));
3390 break;
3391 case Expand:
3392 if (VT != MVT::Vector) {
3393 // If this is a large integer, it needs to be reassembled from small
3394 // integers. Figure out what the source elt type is and how many small
3395 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003396 MVT::ValueType NVT = getTypeToExpandTo(VT);
3397 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003398 for (unsigned i = 0; i != NumVals; ++i)
3399 RetTys.push_back(NVT);
3400 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003401 // Otherwise, this is a vector type. We only support legal vectors
3402 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003403 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003404 unsigned NumElems = PTy->getNumElements();
3405 const Type *EltTy = PTy->getElementType();
3406
3407 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003408 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003409 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3410 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3411 RetTys.push_back(TVT);
3412 } else {
3413 assert(0 && "Don't support illegal by-val vector call results yet!");
3414 abort();
3415 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003416 }
3417 }
3418 }
3419
3420 RetTys.push_back(MVT::Other); // Always has a chain.
3421
3422 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003423 SDOperand Res = DAG.getNode(ISD::CALL,
3424 DAG.getVTList(&RetTys[0], RetTys.size()),
3425 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003426
3427 // This returns a pair of operands. The first element is the
3428 // return value for the function (if RetTy is not VoidTy). The second
3429 // element is the outgoing token chain.
3430 SDOperand ResVal;
3431 if (RetTys.size() != 1) {
3432 MVT::ValueType VT = getValueType(RetTy);
3433 if (RetTys.size() == 2) {
3434 ResVal = Res;
3435
3436 // If this value was promoted, truncate it down.
3437 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003438 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003439 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003440 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003441 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3442 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003443
3444 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003445 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003446 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003447 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003448 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3449 // "N x PTyElementVT" MVT::Vector type.
3450 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003451 DAG.getConstant(NumElems, MVT::i32),
3452 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003453 } else {
3454 abort();
3455 }
3456 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003457 unsigned AssertOp = ISD::AssertSext;
3458 if (!RetTyIsSigned)
3459 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003460 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3461 DAG.getValueType(VT));
3462 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3463 } else {
3464 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003465 if (getTypeAction(VT) == Expand)
3466 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3467 else
3468 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003469 }
3470 }
3471 } else if (RetTys.size() == 3) {
3472 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3473 Res.getValue(0), Res.getValue(1));
3474
3475 } else {
3476 assert(0 && "Case not handled yet!");
3477 }
3478 }
3479
3480 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3481}
3482
Chris Lattner29dcc712005-05-14 05:50:48 +00003483SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003484 assert(0 && "LowerOperation not implemented for this target!");
3485 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003486 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003487}
3488
Nate Begeman595ec732006-01-28 03:14:31 +00003489SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3490 SelectionDAG &DAG) {
3491 assert(0 && "CustomPromoteOperation not implemented for this target!");
3492 abort();
3493 return SDOperand();
3494}
3495
Evan Cheng6781b6e2006-02-15 21:59:04 +00003496/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003497/// operand.
3498static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003499 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003500 MVT::ValueType CurVT = VT;
3501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3502 uint64_t Val = C->getValue() & 255;
3503 unsigned Shift = 8;
3504 while (CurVT != MVT::i8) {
3505 Val = (Val << Shift) | Val;
3506 Shift <<= 1;
3507 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003508 }
3509 return DAG.getConstant(Val, VT);
3510 } else {
3511 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3512 unsigned Shift = 8;
3513 while (CurVT != MVT::i8) {
3514 Value =
3515 DAG.getNode(ISD::OR, VT,
3516 DAG.getNode(ISD::SHL, VT, Value,
3517 DAG.getConstant(Shift, MVT::i8)), Value);
3518 Shift <<= 1;
3519 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003520 }
3521
3522 return Value;
3523 }
3524}
3525
Evan Cheng6781b6e2006-02-15 21:59:04 +00003526/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3527/// used when a memcpy is turned into a memset when the source is a constant
3528/// string ptr.
3529static SDOperand getMemsetStringVal(MVT::ValueType VT,
3530 SelectionDAG &DAG, TargetLowering &TLI,
3531 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003532 uint64_t Val = 0;
3533 unsigned MSB = getSizeInBits(VT) / 8;
3534 if (TLI.isLittleEndian())
3535 Offset = Offset + MSB - 1;
3536 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003537 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003538 Offset += TLI.isLittleEndian() ? -1 : 1;
3539 }
3540 return DAG.getConstant(Val, VT);
3541}
3542
Evan Cheng81fcea82006-02-14 08:22:34 +00003543/// getMemBasePlusOffset - Returns base and offset node for the
3544static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3545 SelectionDAG &DAG, TargetLowering &TLI) {
3546 MVT::ValueType VT = Base.getValueType();
3547 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3548}
3549
Evan Chengdb2a7a72006-02-14 20:12:38 +00003550/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003551/// to replace the memset / memcpy is below the threshold. It also returns the
3552/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003553static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3554 unsigned Limit, uint64_t Size,
3555 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003556 MVT::ValueType VT;
3557
3558 if (TLI.allowsUnalignedMemoryAccesses()) {
3559 VT = MVT::i64;
3560 } else {
3561 switch (Align & 7) {
3562 case 0:
3563 VT = MVT::i64;
3564 break;
3565 case 4:
3566 VT = MVT::i32;
3567 break;
3568 case 2:
3569 VT = MVT::i16;
3570 break;
3571 default:
3572 VT = MVT::i8;
3573 break;
3574 }
3575 }
3576
Evan Chengd5026102006-02-14 09:11:59 +00003577 MVT::ValueType LVT = MVT::i64;
3578 while (!TLI.isTypeLegal(LVT))
3579 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3580 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003581
Evan Chengd5026102006-02-14 09:11:59 +00003582 if (VT > LVT)
3583 VT = LVT;
3584
Evan Cheng04514992006-02-14 23:05:54 +00003585 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003586 while (Size != 0) {
3587 unsigned VTSize = getSizeInBits(VT) / 8;
3588 while (VTSize > Size) {
3589 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003590 VTSize >>= 1;
3591 }
Evan Chengd5026102006-02-14 09:11:59 +00003592 assert(MVT::isInteger(VT));
3593
3594 if (++NumMemOps > Limit)
3595 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003596 MemOps.push_back(VT);
3597 Size -= VTSize;
3598 }
Evan Chengd5026102006-02-14 09:11:59 +00003599
3600 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003601}
3602
Chris Lattner875def92005-01-11 05:56:49 +00003603void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003604 SDOperand Op1 = getValue(I.getOperand(1));
3605 SDOperand Op2 = getValue(I.getOperand(2));
3606 SDOperand Op3 = getValue(I.getOperand(3));
3607 SDOperand Op4 = getValue(I.getOperand(4));
3608 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3609 if (Align == 0) Align = 1;
3610
3611 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3612 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003613
3614 // Expand memset / memcpy to a series of load / store ops
3615 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003616 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003617 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003618 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003619 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003620 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3621 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003622 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003623 unsigned Offset = 0;
3624 for (unsigned i = 0; i < NumMemOps; i++) {
3625 MVT::ValueType VT = MemOps[i];
3626 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003627 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003628 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003629 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003630 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003631 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003632 Offset += VTSize;
3633 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003634 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003635 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003636 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003637 case ISD::MEMCPY: {
3638 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3639 Size->getValue(), Align, TLI)) {
3640 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003641 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003642 GlobalAddressSDNode *G = NULL;
3643 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003644 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003645
3646 if (Op2.getOpcode() == ISD::GlobalAddress)
3647 G = cast<GlobalAddressSDNode>(Op2);
3648 else if (Op2.getOpcode() == ISD::ADD &&
3649 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3650 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3651 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003652 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003653 }
3654 if (G) {
3655 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003656 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003657 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003658 if (!Str.empty()) {
3659 CopyFromStr = true;
3660 SrcOff += SrcDelta;
3661 }
3662 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003663 }
3664
Evan Chenge2038bd2006-02-15 01:54:51 +00003665 for (unsigned i = 0; i < NumMemOps; i++) {
3666 MVT::ValueType VT = MemOps[i];
3667 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003668 SDOperand Value, Chain, Store;
3669
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003670 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003671 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3672 Chain = getRoot();
3673 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003674 DAG.getStore(Chain, Value,
3675 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003676 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003677 } else {
3678 Value = DAG.getLoad(VT, getRoot(),
3679 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003680 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003681 Chain = Value.getValue(1);
3682 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003683 DAG.getStore(Chain, Value,
3684 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003685 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003686 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003687 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003688 SrcOff += VTSize;
3689 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003690 }
3691 }
3692 break;
3693 }
3694 }
3695
3696 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003697 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3698 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003699 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003700 }
3701 }
3702
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003703 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003704}
3705
Chris Lattner875def92005-01-11 05:56:49 +00003706//===----------------------------------------------------------------------===//
3707// SelectionDAGISel code
3708//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003709
3710unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3711 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3712}
3713
Chris Lattnerc9950c12005-08-17 06:37:43 +00003714void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003715 // FIXME: we only modify the CFG to split critical edges. This
3716 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003717 AU.addRequired<AliasAnalysis>();
Evan Cheng009ea542007-03-16 08:46:27 +00003718 AU.addRequired<LoopInfo>();
3719 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003720}
Chris Lattner7a60d912005-01-07 07:47:53 +00003721
Chris Lattner35397782005-12-05 07:10:48 +00003722
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003723/// OptimizeNoopCopyExpression - We have determined that the specified cast
3724/// instruction is a noop copy (e.g. it's casting from one pointer type to
3725/// another, int->uint, or int->sbyte on PPC.
3726///
3727/// Return true if any changes are made.
3728static bool OptimizeNoopCopyExpression(CastInst *CI) {
3729 BasicBlock *DefBB = CI->getParent();
3730
3731 /// InsertedCasts - Only insert a cast in each block once.
3732 std::map<BasicBlock*, CastInst*> InsertedCasts;
3733
3734 bool MadeChange = false;
3735 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3736 UI != E; ) {
3737 Use &TheUse = UI.getUse();
3738 Instruction *User = cast<Instruction>(*UI);
3739
3740 // Figure out which BB this cast is used in. For PHI's this is the
3741 // appropriate predecessor block.
3742 BasicBlock *UserBB = User->getParent();
3743 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3744 unsigned OpVal = UI.getOperandNo()/2;
3745 UserBB = PN->getIncomingBlock(OpVal);
3746 }
3747
3748 // Preincrement use iterator so we don't invalidate it.
3749 ++UI;
3750
3751 // If this user is in the same block as the cast, don't change the cast.
3752 if (UserBB == DefBB) continue;
3753
3754 // If we have already inserted a cast into this block, use it.
3755 CastInst *&InsertedCast = InsertedCasts[UserBB];
3756
3757 if (!InsertedCast) {
3758 BasicBlock::iterator InsertPt = UserBB->begin();
3759 while (isa<PHINode>(InsertPt)) ++InsertPt;
3760
3761 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003762 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3763 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003764 MadeChange = true;
3765 }
3766
3767 // Replace a use of the cast with a use of the new casat.
3768 TheUse = InsertedCast;
3769 }
3770
3771 // If we removed all uses, nuke the cast.
3772 if (CI->use_empty())
3773 CI->eraseFromParent();
3774
3775 return MadeChange;
3776}
3777
Chris Lattner35397782005-12-05 07:10:48 +00003778/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3779/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003780static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3781 Instruction *GEPI, Value *Ptr,
3782 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003783 if (V) return V; // Already computed.
3784
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003785 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003786 BasicBlock::iterator InsertPt;
3787 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003788 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003789 InsertPt = GEPI;
3790 ++InsertPt;
3791 } else {
3792 // Otherwise, insert at the top of BB, after any PHI nodes
3793 InsertPt = BB->begin();
3794 while (isa<PHINode>(InsertPt)) ++InsertPt;
3795 }
3796
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003797 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3798 // BB so that there is only one value live across basic blocks (the cast
3799 // operand).
3800 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3801 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003802 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3803 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003804
Chris Lattner35397782005-12-05 07:10:48 +00003805 // Add the offset, cast it to the right type.
3806 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003807 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3808 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3809 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003810}
3811
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003812/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3813/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3814/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3815/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3816/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3817/// the constant add into a load or store instruction. Additionally, if a user
3818/// is a pointer-pointer cast, we look through it to find its users.
3819static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3820 Constant *PtrOffset, BasicBlock *DefBB,
3821 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003822 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003823 while (!RepPtr->use_empty()) {
3824 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003825
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003826 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3827 // used for a Pointer-Pointer cast.
3828 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003829 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003830
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003831 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3832 // could invalidate an iterator.
3833 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3834 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003835 }
3836
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003837 // If this is a load of the pointer, or a store through the pointer, emit
3838 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003839 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003840 if (isa<LoadInst>(User) ||
3841 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3842 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3843 User->getParent(), GEPI,
3844 Ptr, PtrOffset);
3845 } else {
3846 // If this use is not foldable into the addressing mode, use a version
3847 // emitted in the GEP block.
3848 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3849 Ptr, PtrOffset);
3850 }
3851
Chris Lattner21cd9902006-05-06 09:10:37 +00003852 if (GEPI->getType() != RepPtr->getType()) {
3853 BasicBlock::iterator IP = NewVal;
3854 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003855 // NewVal must be a GEP which must be pointer type, so BitCast
3856 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00003857 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003858 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003859 }
3860}
Chris Lattner35397782005-12-05 07:10:48 +00003861
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003862
Chris Lattner35397782005-12-05 07:10:48 +00003863/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3864/// selection, we want to be a bit careful about some things. In particular, if
3865/// we have a GEP instruction that is used in a different block than it is
3866/// defined, the addressing expression of the GEP cannot be folded into loads or
3867/// stores that use it. In this case, decompose the GEP and move constant
3868/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003869static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003870 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003871 // If this GEP is only used inside the block it is defined in, there is no
3872 // need to rewrite it.
3873 bool isUsedOutsideDefBB = false;
3874 BasicBlock *DefBB = GEPI->getParent();
3875 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3876 UI != E; ++UI) {
3877 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3878 isUsedOutsideDefBB = true;
3879 break;
3880 }
3881 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003882 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003883
3884 // If this GEP has no non-zero constant indices, there is nothing we can do,
3885 // ignore it.
3886 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003887 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003888 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3889 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003890 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003891 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003892 hasConstantIndex = true;
3893 break;
3894 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003895 } else {
3896 hasVariableIndex = true;
3897 }
Chris Lattner35397782005-12-05 07:10:48 +00003898 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003899
3900 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3901 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003902 /// The GEP operand must be a pointer, so must its result -> BitCast
3903 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003904 GEPI->getName(), GEPI);
3905 GEPI->replaceAllUsesWith(NC);
3906 GEPI->eraseFromParent();
3907 return true;
3908 }
3909
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003910 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003911 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3912 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003913
3914 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3915 // constant offset (which we now know is non-zero) and deal with it later.
3916 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003917 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003918 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003919 const Type *Ty = GEPI->getOperand(0)->getType();
3920
3921 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3922 E = GEPI->op_end(); OI != E; ++OI) {
3923 Value *Idx = *OI;
3924 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003925 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003926 if (Field)
Chris Lattnerc473d8e2007-02-10 19:55:17 +00003927 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner35397782005-12-05 07:10:48 +00003928 Ty = StTy->getElementType(Field);
3929 } else {
3930 Ty = cast<SequentialType>(Ty)->getElementType();
3931
3932 // Handle constant subscripts.
3933 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003934 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00003935 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003936 continue;
3937 }
3938
3939 // Ptr = Ptr + Idx * ElementSize;
3940
3941 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003942 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003943
Owen Anderson20a631f2006-05-03 01:29:57 +00003944 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003945 // Mask off bits that should not be set.
3946 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003947 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003948
3949 // Multiply by the element size and add to the base.
3950 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3951 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3952 }
3953 }
3954
3955 // Make sure that the offset fits in uintptr_t.
3956 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003957 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003958
3959 // Okay, we have now emitted all of the variable index parts to the BB that
3960 // the GEP is defined in. Loop over all of the using instructions, inserting
3961 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003962 // instruction to use the newly computed value, making GEPI dead. When the
3963 // user is a load or store instruction address, we emit the add into the user
3964 // block, otherwise we use a canonical version right next to the gep (these
3965 // won't be foldable as addresses, so we might as well share the computation).
3966
Chris Lattner21cd9902006-05-06 09:10:37 +00003967 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003968 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003969
3970 // Finally, the GEP is dead, remove it.
3971 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003972
3973 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003974}
3975
Evan Cheng009ea542007-03-16 08:46:27 +00003976/// isLoopInvariantInst - Returns true if all operands of the instruction are
3977/// loop invariants in the specified loop.
3978static bool isLoopInvariantInst(Instruction *I, Loop *L) {
3979 // The instruction is loop invariant if all of its operands are loop-invariant
3980 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3981 if (!L->isLoopInvariant(I->getOperand(i)))
3982 return false;
3983 return true;
3984}
3985
3986/// SinkInvariantGEPIndex - If a GEP instruction has a variable index that has
3987/// been hoisted out of the loop by LICM pass, sink it back into the use BB
3988/// if it can be determined that the index computation can be folded into the
3989/// addressing mode of the load / store uses.
3990static bool SinkInvariantGEPIndex(BinaryOperator *BinOp, LoopInfo *loopInfo,
3991 const TargetLowering &TLI) {
Evan Cheng009ea542007-03-16 08:46:27 +00003992 // Only look at Add / Sub for now.
3993 if (BinOp->getOpcode() != Instruction::Add &&
3994 BinOp->getOpcode() != Instruction::Sub)
3995 return false;
3996
Evan Chengbe222352007-03-17 08:22:49 +00003997 // DestBBs - These are the blocks where a copy of BinOp will be inserted.
Evan Chenga2465df2007-03-17 08:53:30 +00003998 SmallSet<BasicBlock*, 8> DestBBs;
Evan Cheng009ea542007-03-16 08:46:27 +00003999 BasicBlock *DefBB = BinOp->getParent();
Evan Chengbe222352007-03-17 08:22:49 +00004000 bool MadeChange = false;
Evan Cheng009ea542007-03-16 08:46:27 +00004001 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
Evan Chengbe222352007-03-17 08:22:49 +00004002 UI != E; ++UI) {
Evan Cheng009ea542007-03-16 08:46:27 +00004003 Instruction *User = cast<Instruction>(*UI);
Evan Cheng009ea542007-03-16 08:46:27 +00004004 // Only look for GEP use in another block.
4005 if (User->getParent() == DefBB) continue;
4006
4007 if (isa<GetElementPtrInst>(User)) {
4008 BasicBlock *UserBB = User->getParent();
4009 Loop *L = loopInfo->getLoopFor(UserBB);
4010
4011 // Only sink if expression is a loop invariant in the use BB.
Evan Cheng0a9d0ca2007-03-16 17:50:20 +00004012 if (L && isLoopInvariantInst(BinOp, L) && !User->use_empty()) {
Evan Cheng009ea542007-03-16 08:46:27 +00004013 const Type *UseTy = NULL;
4014 // FIXME: We are assuming all the uses of the GEP will have the
4015 // same type.
4016 Instruction *GEPUser = cast<Instruction>(*User->use_begin());
4017 if (LoadInst *Load = dyn_cast<LoadInst>(GEPUser))
4018 UseTy = Load->getType();
4019 else if (StoreInst *Store = dyn_cast<StoreInst>(GEPUser))
4020 UseTy = Store->getOperand(0)->getType();
4021
4022 // Check if it is possible to fold the expression to address mode.
4023 if (UseTy &&
Evan Cheng550cf032007-03-20 19:32:11 +00004024 TLI.isLegalAddressExpression(BinOp->getOpcode(),
4025 BinOp->getOperand(0),
Evan Cheng009ea542007-03-16 08:46:27 +00004026 BinOp->getOperand(1), UseTy)) {
Evan Chengbe222352007-03-17 08:22:49 +00004027 DestBBs.insert(UserBB);
Evan Cheng009ea542007-03-16 08:46:27 +00004028 MadeChange = true;
4029 }
4030 }
4031 }
4032 }
4033
Evan Chengbe222352007-03-17 08:22:49 +00004034 // Nothing to do.
4035 if (!MadeChange)
4036 return false;
4037
4038 /// InsertedOps - Only insert a duplicate in each block once.
4039 std::map<BasicBlock*, BinaryOperator*> InsertedOps;
4040 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
4041 UI != E; ) {
4042 Instruction *User = cast<Instruction>(*UI);
4043 BasicBlock *UserBB = User->getParent();
4044
4045 // Preincrement use iterator so we don't invalidate it.
4046 ++UI;
4047
4048 // If any user in this BB wants it, replace all the uses in the BB.
4049 if (DestBBs.count(UserBB)) {
4050 // Sink it into user block.
4051 BinaryOperator *&InsertedOp = InsertedOps[UserBB];
4052 if (!InsertedOp) {
4053 BasicBlock::iterator InsertPt = UserBB->begin();
4054 while (isa<PHINode>(InsertPt)) ++InsertPt;
4055
4056 InsertedOp =
4057 BinaryOperator::create(BinOp->getOpcode(), BinOp->getOperand(0),
4058 BinOp->getOperand(1), "", InsertPt);
4059 }
4060
4061 User->replaceUsesOfWith(BinOp, InsertedOp);
4062 }
4063 }
4064
Evan Cheng009ea542007-03-16 08:46:27 +00004065 if (BinOp->use_empty())
4066 BinOp->eraseFromParent();
4067
Evan Chengbe222352007-03-17 08:22:49 +00004068 return true;
Evan Cheng009ea542007-03-16 08:46:27 +00004069}
4070
Chris Lattnerbba52192006-10-28 19:22:10 +00004071
4072/// SplitEdgeNicely - Split the critical edge from TI to it's specified
4073/// successor if it will improve codegen. We only do this if the successor has
4074/// phi nodes (otherwise critical edges are ok). If there is already another
4075/// predecessor of the succ that is empty (and thus has no phi nodes), use it
4076/// instead of introducing a new block.
4077static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
4078 BasicBlock *TIBB = TI->getParent();
4079 BasicBlock *Dest = TI->getSuccessor(SuccNum);
4080 assert(isa<PHINode>(Dest->begin()) &&
4081 "This should only be called if Dest has a PHI!");
4082
4083 /// TIPHIValues - This array is lazily computed to determine the values of
4084 /// PHIs in Dest that TI would provide.
4085 std::vector<Value*> TIPHIValues;
4086
4087 // Check to see if Dest has any blocks that can be used as a split edge for
4088 // this terminator.
4089 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
4090 BasicBlock *Pred = *PI;
4091 // To be usable, the pred has to end with an uncond branch to the dest.
4092 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
4093 if (!PredBr || !PredBr->isUnconditional() ||
4094 // Must be empty other than the branch.
4095 &Pred->front() != PredBr)
4096 continue;
4097
4098 // Finally, since we know that Dest has phi nodes in it, we have to make
4099 // sure that jumping to Pred will have the same affect as going to Dest in
4100 // terms of PHI values.
4101 PHINode *PN;
4102 unsigned PHINo = 0;
4103 bool FoundMatch = true;
4104 for (BasicBlock::iterator I = Dest->begin();
4105 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
4106 if (PHINo == TIPHIValues.size())
4107 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
4108
4109 // If the PHI entry doesn't work, we can't use this pred.
4110 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
4111 FoundMatch = false;
4112 break;
4113 }
4114 }
4115
4116 // If we found a workable predecessor, change TI to branch to Succ.
4117 if (FoundMatch) {
4118 Dest->removePredecessor(TIBB);
4119 TI->setSuccessor(SuccNum, Pred);
4120 return;
4121 }
4122 }
4123
4124 SplitCriticalEdge(TI, SuccNum, P, true);
4125}
4126
4127
Chris Lattner7a60d912005-01-07 07:47:53 +00004128bool SelectionDAGISel::runOnFunction(Function &Fn) {
4129 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4130 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004131 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004132
Evan Cheng009ea542007-03-16 08:46:27 +00004133 LoopInfo *loopInfo = &getAnalysis<LoopInfo>();
4134
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004135 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00004136 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004137 // In this pass we also look for GEP and cast instructions that are used
4138 // across basic blocks and rewrite them to improve basic-block-at-a-time
4139 // selection.
4140 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004141 bool MadeChange = true;
4142 while (MadeChange) {
4143 MadeChange = false;
Evan Chengde608342007-02-10 01:08:18 +00004144 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbba52192006-10-28 19:22:10 +00004145 // Split all critical edges where the dest block has a PHI.
Evan Chengde608342007-02-10 01:08:18 +00004146 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004147 if (BBTI->getNumSuccessors() > 1) {
4148 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00004149 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4150 isCriticalEdge(BBTI, i, true))
4151 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004152 }
4153
Chris Lattner35397782005-12-05 07:10:48 +00004154
Evan Chengde608342007-02-10 01:08:18 +00004155 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004156 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00004157
4158 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4159 // If we found an inline asm expession, and if the target knows how to
4160 // lower it to normal LLVM code, do so now.
4161 if (isa<InlineAsm>(CI->getCalledValue()))
4162 if (const TargetAsmInfo *TAI =
4163 TLI.getTargetMachine().getTargetAsmInfo()) {
4164 if (TAI->ExpandInlineAsm(CI))
Evan Chengde608342007-02-10 01:08:18 +00004165 BBI = FNI->begin();
Chris Lattner90f42382006-11-29 01:12:32 +00004166 }
4167 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004168 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004169 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00004170 // If the source of the cast is a constant, then this should have
4171 // already been constant folded. The only reason NOT to constant fold
4172 // it is if something (e.g. LSR) was careful to place the constant
4173 // evaluation in a block other than then one that uses it (e.g. to hoist
4174 // the address of globals out of a loop). If this is the case, we don't
4175 // want to forward-subst the cast.
4176 if (isa<Constant>(CI->getOperand(0)))
4177 continue;
4178
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004179 // If this is a noop copy, sink it into user blocks to reduce the number
4180 // of virtual registers that must be created and coallesced.
4181 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4182 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4183
4184 // This is an fp<->int conversion?
4185 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4186 continue;
4187
4188 // If this is an extension, it will be a zero or sign extension, which
4189 // isn't a noop.
4190 if (SrcVT < DstVT) continue;
4191
4192 // If these values will be promoted, find out what they will be promoted
4193 // to. This helps us consider truncates on PPC as noop copies when they
4194 // are.
4195 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4196 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4197 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4198 DstVT = TLI.getTypeToTransformTo(DstVT);
4199
4200 // If, after promotion, these are the same types, this is a noop copy.
4201 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004202 MadeChange |= OptimizeNoopCopyExpression(CI);
Evan Cheng009ea542007-03-16 08:46:27 +00004203 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I)) {
4204 MadeChange |= SinkInvariantGEPIndex(BinOp, loopInfo, TLI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004205 }
4206 }
Chris Lattner1a908c82005-08-18 17:35:14 +00004207 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004208 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00004209
Chris Lattner7a60d912005-01-07 07:47:53 +00004210 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4211
4212 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4213 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004214
Evan Cheng276b44b2007-02-10 02:43:39 +00004215 // Add function live-ins to entry block live-in set.
4216 BasicBlock *EntryBB = &Fn.getEntryBlock();
4217 BB = FuncInfo.MBBMap[EntryBB];
4218 if (!MF.livein_empty())
4219 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4220 E = MF.livein_end(); I != E; ++I)
4221 BB->addLiveIn(I->first);
4222
Chris Lattner7a60d912005-01-07 07:47:53 +00004223 return true;
4224}
4225
Chris Lattnered0110b2006-10-27 21:36:01 +00004226SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4227 unsigned Reg) {
4228 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004229 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004230 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004231 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004232
4233 // If this type is not legal, we must make sure to not create an invalid
4234 // register use.
4235 MVT::ValueType SrcVT = Op.getValueType();
4236 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004237 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004238 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004239 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004240 // Handle copies from generic vectors to registers.
4241 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004242 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004243 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004244
Chris Lattner5fe1f542006-03-31 02:06:56 +00004245 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4246 // MVT::Vector type.
4247 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4248 DAG.getConstant(NE, MVT::i32),
4249 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004250
Chris Lattner5fe1f542006-03-31 02:06:56 +00004251 // Loop over all of the elements of the resultant vector,
4252 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4253 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004254 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004255 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004256 for (unsigned i = 0; i != NE; ++i) {
4257 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004258 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004259 if (PTyElementVT == PTyLegalElementVT) {
4260 // Elements are legal.
4261 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4262 } else if (PTyLegalElementVT > PTyElementVT) {
4263 // Elements are promoted.
4264 if (MVT::isFloatingPoint(PTyLegalElementVT))
4265 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4266 else
4267 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4268 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4269 } else {
4270 // Elements are expanded.
4271 // The src value is expanded into multiple registers.
4272 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004273 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004274 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004275 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004276 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4277 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4278 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004279 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004280 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4281 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004282 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004283 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004284 if (MVT::isFloatingPoint(SrcVT))
4285 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4286 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004287 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004288 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004289 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004290 DestVT = TLI.getTypeToExpandTo(SrcVT);
4291 unsigned NumVals = TLI.getNumElements(SrcVT);
4292 if (NumVals == 1)
4293 return DAG.getCopyToReg(getRoot(), Reg,
4294 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4295 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004296 // The src value is expanded into multiple registers.
4297 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004298 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004299 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004300 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004301 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004302 return DAG.getCopyToReg(Op, Reg+1, Hi);
4303 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004304}
4305
Chris Lattner16f64df2005-01-17 17:15:02 +00004306void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004307LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004308 std::vector<SDOperand> &UnorderedChains) {
4309 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004310 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004311 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004312 SDOperand OldRoot = SDL.DAG.getRoot();
4313 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004314
Chris Lattner6871b232005-10-30 19:42:35 +00004315 unsigned a = 0;
4316 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4317 AI != E; ++AI, ++a)
4318 if (!AI->use_empty()) {
4319 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004320
Chris Lattner6871b232005-10-30 19:42:35 +00004321 // If this argument is live outside of the entry block, insert a copy from
4322 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004323 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4324 if (VMI != FuncInfo.ValueMap.end()) {
4325 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004326 UnorderedChains.push_back(Copy);
4327 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004328 }
Chris Lattner6871b232005-10-30 19:42:35 +00004329
Chris Lattner6871b232005-10-30 19:42:35 +00004330 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004331 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004332 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004333}
4334
Chris Lattner7a60d912005-01-07 07:47:53 +00004335void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4336 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004337 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004338 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004339
4340 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004341
Chris Lattner6871b232005-10-30 19:42:35 +00004342 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004343 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004344 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004345
4346 BB = FuncInfo.MBBMap[LLVMBB];
4347 SDL.setCurrentBasicBlock(BB);
4348
4349 // Lower all of the non-terminator instructions.
4350 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4351 I != E; ++I)
4352 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004353
4354 // Lower call part of invoke.
4355 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4356 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004357
Chris Lattner7a60d912005-01-07 07:47:53 +00004358 // Ensure that all instructions which are used outside of their defining
4359 // blocks are available as virtual registers.
4360 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004361 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004362 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004363 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004364 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004365 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004366 }
4367
4368 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4369 // ensure constants are generated when needed. Remember the virtual registers
4370 // that need to be added to the Machine PHI nodes as input. We cannot just
4371 // directly add them, because expansion might result in multiple MBB's for one
4372 // BB. As such, the start of the BB might correspond to a different MBB than
4373 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004374 //
Chris Lattner84a03502006-10-27 23:50:33 +00004375 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004376
4377 // Emit constants only once even if used by multiple PHI nodes.
4378 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004379
Chris Lattner84a03502006-10-27 23:50:33 +00004380 // Vector bool would be better, but vector<bool> is really slow.
4381 std::vector<unsigned char> SuccsHandled;
4382 if (TI->getNumSuccessors())
4383 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4384
Chris Lattner7a60d912005-01-07 07:47:53 +00004385 // Check successor nodes PHI nodes that expect a constant to be available from
4386 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004387 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4388 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004389 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004390 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004391
Chris Lattner84a03502006-10-27 23:50:33 +00004392 // If this terminator has multiple identical successors (common for
4393 // switches), only handle each succ once.
4394 unsigned SuccMBBNo = SuccMBB->getNumber();
4395 if (SuccsHandled[SuccMBBNo]) continue;
4396 SuccsHandled[SuccMBBNo] = true;
4397
4398 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004399 PHINode *PN;
4400
4401 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4402 // nodes and Machine PHI nodes, but the incoming operands have not been
4403 // emitted yet.
4404 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004405 (PN = dyn_cast<PHINode>(I)); ++I) {
4406 // Ignore dead phi's.
4407 if (PN->use_empty()) continue;
4408
4409 unsigned Reg;
4410 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004411
Chris Lattner84a03502006-10-27 23:50:33 +00004412 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4413 unsigned &RegOut = ConstantsOut[C];
4414 if (RegOut == 0) {
4415 RegOut = FuncInfo.CreateRegForValue(C);
4416 UnorderedChains.push_back(
4417 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004418 }
Chris Lattner84a03502006-10-27 23:50:33 +00004419 Reg = RegOut;
4420 } else {
4421 Reg = FuncInfo.ValueMap[PHIOp];
4422 if (Reg == 0) {
4423 assert(isa<AllocaInst>(PHIOp) &&
4424 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4425 "Didn't codegen value into a register!??");
4426 Reg = FuncInfo.CreateRegForValue(PHIOp);
4427 UnorderedChains.push_back(
4428 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004429 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004430 }
Chris Lattner84a03502006-10-27 23:50:33 +00004431
4432 // Remember that this register needs to added to the machine PHI node as
4433 // the input for this MBB.
4434 MVT::ValueType VT = TLI.getValueType(PN->getType());
4435 unsigned NumElements;
4436 if (VT != MVT::Vector)
4437 NumElements = TLI.getNumElements(VT);
4438 else {
4439 MVT::ValueType VT1,VT2;
4440 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004441 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004442 VT1, VT2);
4443 }
4444 for (unsigned i = 0, e = NumElements; i != e; ++i)
4445 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4446 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004447 }
4448 ConstantsOut.clear();
4449
Chris Lattner718b5c22005-01-13 17:59:43 +00004450 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004451 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004452 SDOperand Root = SDL.getRoot();
4453 if (Root.getOpcode() != ISD::EntryToken) {
4454 unsigned i = 0, e = UnorderedChains.size();
4455 for (; i != e; ++i) {
4456 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4457 if (UnorderedChains[i].Val->getOperand(0) == Root)
4458 break; // Don't add the root if we already indirectly depend on it.
4459 }
4460
4461 if (i == e)
4462 UnorderedChains.push_back(Root);
4463 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004464 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4465 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004466 }
4467
Chris Lattner7a60d912005-01-07 07:47:53 +00004468 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004469 if (Invoke) {
4470 // Just the branch part of invoke.
4471 SDL.visitInvoke(*Invoke, true);
4472 } else {
4473 SDL.visit(*LLVMBB->getTerminator());
4474 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004475
Nate Begemaned728c12006-03-27 01:32:24 +00004476 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004477 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004478 SwitchCases.clear();
4479 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004480 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00004481
Chris Lattner4108bb02005-01-17 19:43:36 +00004482 // Make sure the root of the DAG is up-to-date.
4483 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004484}
4485
Nate Begemaned728c12006-03-27 01:32:24 +00004486void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004487 // Get alias analysis for load/store combining.
4488 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4489
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004490 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004491 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004492
Bill Wendling22e978a2006-12-07 20:04:42 +00004493 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004494 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004495
Chris Lattner7a60d912005-01-07 07:47:53 +00004496 // Second step, hack on the DAG until it only uses operations and types that
4497 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004498 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004499
Bill Wendling22e978a2006-12-07 20:04:42 +00004500 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004501 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004502
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004503 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004504 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004505
Evan Cheng739a6a42006-01-21 02:32:06 +00004506 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004507
Chris Lattner5ca31d92005-03-30 01:10:47 +00004508 // Third, instruction select all of the operations to machine code, adding the
4509 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004510 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004511
Bill Wendling22e978a2006-12-07 20:04:42 +00004512 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004513 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004514}
Chris Lattner7a60d912005-01-07 07:47:53 +00004515
Nate Begemaned728c12006-03-27 01:32:24 +00004516void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4517 FunctionLoweringInfo &FuncInfo) {
4518 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4519 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004520 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004521 CurDAG = &DAG;
4522
4523 // First step, lower LLVM code to some DAG. This DAG may use operations and
4524 // types that are not supported by the target.
4525 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4526
4527 // Second step, emit the lowered DAG as machine code.
4528 CodeGenAndEmitDAG(DAG);
4529 }
4530
Chris Lattner5ca31d92005-03-30 01:10:47 +00004531 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004532 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004533 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00004534 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4535 MachineInstr *PHI = PHINodesToUpdate[i].first;
4536 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4537 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004538 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004539 PHI->addMachineBasicBlockOperand(BB);
4540 }
4541 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004542 }
Nate Begemaned728c12006-03-27 01:32:24 +00004543
Nate Begeman866b4b42006-04-23 06:26:20 +00004544 // If the JumpTable record is filled in, then we need to emit a jump table.
4545 // Updating the PHI nodes is tricky in this case, since we need to determine
4546 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004547 if (JT.Reg) {
4548 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskeyc56315c2007-01-26 21:22:28 +00004549 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004550 CurDAG = &SDAG;
4551 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00004552 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004553 // Set the current basic block to the mbb we wish to insert the code into
4554 BB = JT.MBB;
4555 SDL.setCurrentBasicBlock(BB);
4556 // Emit the code
4557 SDL.visitJumpTable(JT);
4558 SDAG.setRoot(SDL.getRoot());
4559 CodeGenAndEmitDAG(SDAG);
4560 // Update PHI Nodes
4561 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4562 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4563 MachineBasicBlock *PHIBB = PHI->getParent();
4564 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4565 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00004566 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004567 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004568 PHI->addMachineBasicBlockOperand(RangeBB);
4569 }
4570 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004571 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004572 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004573 }
4574 }
4575 return;
4576 }
4577
Chris Lattner76a7bc82006-10-22 23:00:53 +00004578 // If the switch block involved a branch to one of the actual successors, we
4579 // need to update PHI nodes in that block.
4580 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4581 MachineInstr *PHI = PHINodesToUpdate[i].first;
4582 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4583 "This is not a machine PHI node that we are updating!");
4584 if (BB->isSuccessor(PHI->getParent())) {
4585 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4586 PHI->addMachineBasicBlockOperand(BB);
4587 }
4588 }
4589
Nate Begemaned728c12006-03-27 01:32:24 +00004590 // If we generated any switch lowering information, build and codegen any
4591 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004592 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004593 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004594 CurDAG = &SDAG;
4595 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004596
Nate Begemaned728c12006-03-27 01:32:24 +00004597 // Set the current basic block to the mbb we wish to insert the code into
4598 BB = SwitchCases[i].ThisBB;
4599 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004600
Nate Begemaned728c12006-03-27 01:32:24 +00004601 // Emit the code
4602 SDL.visitSwitchCase(SwitchCases[i]);
4603 SDAG.setRoot(SDL.getRoot());
4604 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004605
4606 // Handle any PHI nodes in successors of this chunk, as if we were coming
4607 // from the original BB before switch expansion. Note that PHI nodes can
4608 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4609 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004610 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004611 for (MachineBasicBlock::iterator Phi = BB->begin();
4612 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4613 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4614 for (unsigned pn = 0; ; ++pn) {
4615 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4616 if (PHINodesToUpdate[pn].first == Phi) {
4617 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4618 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4619 break;
4620 }
4621 }
Nate Begemaned728c12006-03-27 01:32:24 +00004622 }
Chris Lattner707339a52006-09-07 01:59:34 +00004623
4624 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004625 if (BB == SwitchCases[i].FalseBB)
4626 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004627
4628 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004629 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004630 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004631 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004632 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004633 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004634}
Evan Cheng739a6a42006-01-21 02:32:06 +00004635
Jim Laskey95eda5b2006-08-01 14:21:23 +00004636
Evan Cheng739a6a42006-01-21 02:32:06 +00004637//===----------------------------------------------------------------------===//
4638/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4639/// target node in the graph.
4640void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4641 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004642
Jim Laskey29e635d2006-08-02 12:30:23 +00004643 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004644
4645 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004646 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004647 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004648 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004649
Jim Laskey03593f72006-08-01 18:29:48 +00004650 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004651 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004652 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004653}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004654
Chris Lattner47639db2006-03-06 00:22:00 +00004655
Jim Laskey03593f72006-08-01 18:29:48 +00004656HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4657 return new HazardRecognizer();
4658}
4659
Chris Lattner6df34962006-10-11 03:58:02 +00004660//===----------------------------------------------------------------------===//
4661// Helper functions used by the generated instruction selector.
4662//===----------------------------------------------------------------------===//
4663// Calls to these methods are generated by tblgen.
4664
4665/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4666/// the dag combiner simplified the 255, we still want to match. RHS is the
4667/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4668/// specified in the .td file (e.g. 255).
4669bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4670 int64_t DesiredMaskS) {
4671 uint64_t ActualMask = RHS->getValue();
4672 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4673
4674 // If the actual mask exactly matches, success!
4675 if (ActualMask == DesiredMask)
4676 return true;
4677
4678 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4679 if (ActualMask & ~DesiredMask)
4680 return false;
4681
4682 // Otherwise, the DAG Combiner may have proven that the value coming in is
4683 // either already zero or is not demanded. Check for known zero input bits.
4684 uint64_t NeededMask = DesiredMask & ~ActualMask;
4685 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4686 return true;
4687
4688 // TODO: check to see if missing bits are just not demanded.
4689
4690 // Otherwise, this pattern doesn't match.
4691 return false;
4692}
4693
4694/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4695/// the dag combiner simplified the 255, we still want to match. RHS is the
4696/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4697/// specified in the .td file (e.g. 255).
4698bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4699 int64_t DesiredMaskS) {
4700 uint64_t ActualMask = RHS->getValue();
4701 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4702
4703 // If the actual mask exactly matches, success!
4704 if (ActualMask == DesiredMask)
4705 return true;
4706
4707 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4708 if (ActualMask & ~DesiredMask)
4709 return false;
4710
4711 // Otherwise, the DAG Combiner may have proven that the value coming in is
4712 // either already zero or is not demanded. Check for known zero input bits.
4713 uint64_t NeededMask = DesiredMask & ~ActualMask;
4714
4715 uint64_t KnownZero, KnownOne;
4716 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4717
4718 // If all the missing bits in the or are already known to be set, match!
4719 if ((NeededMask & KnownOne) == NeededMask)
4720 return true;
4721
4722 // TODO: check to see if missing bits are just not demanded.
4723
4724 // Otherwise, this pattern doesn't match.
4725 return false;
4726}
4727
Jim Laskey03593f72006-08-01 18:29:48 +00004728
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004729/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4730/// by tblgen. Others should not call it.
4731void SelectionDAGISel::
4732SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4733 std::vector<SDOperand> InOps;
4734 std::swap(InOps, Ops);
4735
4736 Ops.push_back(InOps[0]); // input chain.
4737 Ops.push_back(InOps[1]); // input asm string.
4738
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004739 unsigned i = 2, e = InOps.size();
4740 if (InOps[e-1].getValueType() == MVT::Flag)
4741 --e; // Don't process a flag operand if it is here.
4742
4743 while (i != e) {
4744 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4745 if ((Flags & 7) != 4 /*MEM*/) {
4746 // Just skip over this operand, copying the operands verbatim.
4747 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4748 i += (Flags >> 3) + 1;
4749 } else {
4750 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4751 // Otherwise, this is a memory operand. Ask the target to select it.
4752 std::vector<SDOperand> SelOps;
4753 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004754 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004755 exit(1);
4756 }
4757
4758 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004759 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4760 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004761 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4762 i += 2;
4763 }
4764 }
4765
4766 // Add the flag input back if present.
4767 if (e != InOps.size())
4768 Ops.push_back(InOps.back());
4769}