blob: fa4407def528933ba62af929ea4cce860de2bff2 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Jim Laskey29e635d2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Misha Brukman835702a2005-04-21 22:36:52 +0000187
Chris Lattner49409cb2006-03-16 19:51:18 +0000188 unsigned CreateRegForValue(const Value *V);
189
Chris Lattner7a60d912005-01-07 07:47:53 +0000190 unsigned InitializeRegForValue(const Value *V) {
191 unsigned &R = ValueMap[V];
192 assert(R == 0 && "Already initialized this value register!");
193 return R = CreateRegForValue(V);
194 }
195 };
196}
197
198/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000199/// PHI nodes or outside of the basic block that defines it, or used by a
200/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000201static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
202 if (isa<PHINode>(I)) return true;
203 BasicBlock *BB = I->getParent();
204 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000205 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
206 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 return true;
208 return false;
209}
210
Chris Lattner6871b232005-10-30 19:42:35 +0000211/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000212/// entry block, return true. This includes arguments used by switches, since
213/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000214static bool isOnlyUsedInEntryBlock(Argument *A) {
215 BasicBlock *Entry = A->getParent()->begin();
216 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000217 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000218 return false; // Use not in entry block.
219 return true;
220}
221
Chris Lattner7a60d912005-01-07 07:47:53 +0000222FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000223 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
225
Chris Lattner6871b232005-10-30 19:42:35 +0000226 // Create a vreg for each argument register that is not dead and is used
227 // outside of the entry block for the function.
228 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
229 AI != E; ++AI)
230 if (!isOnlyUsedInEntryBlock(AI))
231 InitializeRegForValue(AI);
232
Chris Lattner7a60d912005-01-07 07:47:53 +0000233 // Initialize the mapping of values to registers. This is only set up for
234 // instruction values that are used outside of the block that defines
235 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000236 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
238 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000239 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000241 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000242 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000243 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000244 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000245
Reid Spencere0fc4df2006-10-20 07:07:24 +0000246 // If the alignment of the value is smaller than the size of the
247 // value, and if the size of the value is particularly small
248 // (<= 8 bytes), round up to the size of the value for potentially
249 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000250 //
251 // FIXME: This could be made better with a preferred alignment hook in
252 // TargetData. It serves primarily to 8-byte align doubles for X86.
253 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000254 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000255 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000257 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 }
259
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (; BB != EB; ++BB)
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000262 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
263 if (!isa<AllocaInst>(I) ||
264 !StaticAllocaMap.count(cast<AllocaInst>(I)))
265 InitializeRegForValue(I);
266
267 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
268 // also creates the initial PHI MachineInstrs, though none of the input
269 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000270 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000271 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
272 MBBMap[BB] = MBB;
273 MF.getBasicBlockList().push_back(MBB);
274
275 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
276 // appropriate.
277 PHINode *PN;
278 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000279 (PN = dyn_cast<PHINode>(I)); ++I)
280 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000281 MVT::ValueType VT = TLI.getValueType(PN->getType());
282 unsigned NumElements;
283 if (VT != MVT::Vector)
284 NumElements = TLI.getNumElements(VT);
285 else {
286 MVT::ValueType VT1,VT2;
287 NumElements =
288 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
289 VT1, VT2);
290 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000291 unsigned PHIReg = ValueMap[PN];
292 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
293 for (unsigned i = 0; i != NumElements; ++i)
294 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
295 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000296 }
297}
298
Chris Lattner49409cb2006-03-16 19:51:18 +0000299/// CreateRegForValue - Allocate the appropriate number of virtual registers of
300/// the correctly promoted or expanded types. Assign these registers
301/// consecutive vreg numbers and return the first assigned number.
302unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
303 MVT::ValueType VT = TLI.getValueType(V->getType());
304
305 // The number of multiples of registers that we need, to, e.g., split up
306 // a <2 x int64> -> 4 x i32 registers.
307 unsigned NumVectorRegs = 1;
308
309 // If this is a packed type, figure out what type it will decompose into
310 // and how many of the elements it will use.
311 if (VT == MVT::Vector) {
312 const PackedType *PTy = cast<PackedType>(V->getType());
313 unsigned NumElts = PTy->getNumElements();
314 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
315
316 // Divide the input until we get to a supported size. This will always
317 // end with a scalar if the target doesn't support vectors.
318 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
319 NumElts >>= 1;
320 NumVectorRegs <<= 1;
321 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000322 if (NumElts == 1)
323 VT = EltTy;
324 else
325 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000326 }
327
328 // The common case is that we will only create one register for this
329 // value. If we have that case, create and return the virtual register.
330 unsigned NV = TLI.getNumElements(VT);
331 if (NV == 1) {
332 // If we are promoting this value, pick the next largest supported type.
333 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
334 unsigned Reg = MakeReg(PromotedType);
335 // If this is a vector of supported or promoted types (e.g. 4 x i16),
336 // create all of the registers.
337 for (unsigned i = 1; i != NumVectorRegs; ++i)
338 MakeReg(PromotedType);
339 return Reg;
340 }
341
342 // If this value is represented with multiple target registers, make sure
343 // to create enough consecutive registers of the right (smaller) type.
344 unsigned NT = VT-1; // Find the type to use.
345 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
346 --NT;
347
348 unsigned R = MakeReg((MVT::ValueType)NT);
349 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
350 MakeReg((MVT::ValueType)NT);
351 return R;
352}
Chris Lattner7a60d912005-01-07 07:47:53 +0000353
354//===----------------------------------------------------------------------===//
355/// SelectionDAGLowering - This is the common target-independent lowering
356/// implementation that is parameterized by a TargetLowering object.
357/// Also, targets can overload any lowering method.
358///
359namespace llvm {
360class SelectionDAGLowering {
361 MachineBasicBlock *CurMBB;
362
363 std::map<const Value*, SDOperand> NodeMap;
364
Chris Lattner4d9651c2005-01-17 22:19:26 +0000365 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
366 /// them up and then emit token factor nodes when possible. This allows us to
367 /// get simple disambiguation between loads without worrying about alias
368 /// analysis.
369 std::vector<SDOperand> PendingLoads;
370
Nate Begemaned728c12006-03-27 01:32:24 +0000371 /// Case - A pair of values to record the Value for a switch case, and the
372 /// case's target basic block.
373 typedef std::pair<Constant*, MachineBasicBlock*> Case;
374 typedef std::vector<Case>::iterator CaseItr;
375 typedef std::pair<CaseItr, CaseItr> CaseRange;
376
377 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
378 /// of conditional branches.
379 struct CaseRec {
380 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
381 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
382
383 /// CaseBB - The MBB in which to emit the compare and branch
384 MachineBasicBlock *CaseBB;
385 /// LT, GE - If nonzero, we know the current case value must be less-than or
386 /// greater-than-or-equal-to these Constants.
387 Constant *LT;
388 Constant *GE;
389 /// Range - A pair of iterators representing the range of case values to be
390 /// processed at this point in the binary search tree.
391 CaseRange Range;
392 };
393
394 /// The comparison function for sorting Case values.
395 struct CaseCmp {
396 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000397 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
398 if (I1->getType()->isUnsigned())
399 return I1->getZExtValue() <
400 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000401
Reid Spencere0fc4df2006-10-20 07:07:24 +0000402 return cast<const ConstantInt>(C1.first)->getSExtValue() <
403 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000404 }
405 };
406
Chris Lattner7a60d912005-01-07 07:47:53 +0000407public:
408 // TLI - This is information that describes the available target features we
409 // need for lowering. This indicates when operations are unavailable,
410 // implemented with a libcall, etc.
411 TargetLowering &TLI;
412 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000413 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000414
Nate Begemaned728c12006-03-27 01:32:24 +0000415 /// SwitchCases - Vector of CaseBlock structures used to communicate
416 /// SwitchInst code generation information.
417 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000418 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000419
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 /// FuncInfo - Information about the function as a whole.
421 ///
422 FunctionLoweringInfo &FuncInfo;
423
424 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000425 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000426 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000427 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 }
429
Chris Lattner4108bb02005-01-17 19:43:36 +0000430 /// getRoot - Return the current virtual root of the Selection DAG.
431 ///
432 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000433 if (PendingLoads.empty())
434 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000435
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 if (PendingLoads.size() == 1) {
437 SDOperand Root = PendingLoads[0];
438 DAG.setRoot(Root);
439 PendingLoads.clear();
440 return Root;
441 }
442
443 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000444 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
445 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000446 PendingLoads.clear();
447 DAG.setRoot(Root);
448 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000449 }
450
Chris Lattner7a60d912005-01-07 07:47:53 +0000451 void visit(Instruction &I) { visit(I.getOpcode(), I); }
452
453 void visit(unsigned Opcode, User &I) {
454 switch (Opcode) {
455 default: assert(0 && "Unknown instruction type encountered!");
456 abort();
457 // Build the switch statement using the Instruction.def file.
458#define HANDLE_INST(NUM, OPCODE, CLASS) \
459 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
460#include "llvm/Instruction.def"
461 }
462 }
463
464 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
465
Chris Lattner4024c002006-03-15 22:19:46 +0000466 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000467 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000468 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
470 SDOperand getIntPtrConstant(uint64_t Val) {
471 return DAG.getConstant(Val, TLI.getPointerTy());
472 }
473
Chris Lattner8471b152006-03-16 19:57:50 +0000474 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000475
476 const SDOperand &setValue(const Value *V, SDOperand NewN) {
477 SDOperand &N = NodeMap[V];
478 assert(N.Val == 0 && "Already set a value for this node!");
479 return N = NewN;
480 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000481
Chris Lattner6f87d182006-02-22 22:37:12 +0000482 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
483 MVT::ValueType VT,
484 bool OutReg, bool InReg,
485 std::set<unsigned> &OutputRegs,
486 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemaned728c12006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Nate Begemanb2e089c2005-11-19 00:36:38 +0000502 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000503 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000504 void visitAdd(User &I) {
505 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000506 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000507 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000508 void visitMul(User &I) {
509 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000510 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000512 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000513 visitBinary(I,
514 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
515 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 }
517 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000518 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000521 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
522 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
523 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000524 void visitShl(User &I) { visitShift(I, ISD::SHL); }
525 void visitShr(User &I) {
526 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527 }
528
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000529 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
530 ISD::CondCode FPOpc);
531 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
532 ISD::SETOEQ); }
533 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
534 ISD::SETUNE); }
535 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
536 ISD::SETOLE); }
537 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
538 ISD::SETOGE); }
539 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
540 ISD::SETOLT); }
541 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
542 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
Chris Lattner67271862006-03-29 00:11:43 +0000544 void visitExtractElement(User &I);
545 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000546 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000547
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 void visitGetElementPtr(User &I);
549 void visitCast(User &I);
550 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000551
552 void visitMalloc(MallocInst &I);
553 void visitFree(FreeInst &I);
554 void visitAlloca(AllocaInst &I);
555 void visitLoad(LoadInst &I);
556 void visitStore(StoreInst &I);
557 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
558 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000559 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000560 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000561 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000562
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000564 void visitVAArg(VAArgInst &I);
565 void visitVAEnd(CallInst &I);
566 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000567 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568
Chris Lattner875def92005-01-11 05:56:49 +0000569 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000570
571 void visitUserOp1(Instruction &I) {
572 assert(0 && "UserOp1 should not exist at instruction selection time!");
573 abort();
574 }
575 void visitUserOp2(Instruction &I) {
576 assert(0 && "UserOp2 should not exist at instruction selection time!");
577 abort();
578 }
579};
580} // end namespace llvm
581
Chris Lattner8471b152006-03-16 19:57:50 +0000582SDOperand SelectionDAGLowering::getValue(const Value *V) {
583 SDOperand &N = NodeMap[V];
584 if (N.Val) return N;
585
586 const Type *VTy = V->getType();
587 MVT::ValueType VT = TLI.getValueType(VTy);
588 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
590 visit(CE->getOpcode(), *CE);
591 assert(N.Val && "visit didn't populate the ValueMap!");
592 return N;
593 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
594 return N = DAG.getGlobalAddress(GV, VT);
595 } else if (isa<ConstantPointerNull>(C)) {
596 return N = DAG.getConstant(0, TLI.getPointerTy());
597 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000598 if (!isa<PackedType>(VTy))
599 return N = DAG.getNode(ISD::UNDEF, VT);
600
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000601 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000602 const PackedType *PTy = cast<PackedType>(VTy);
603 unsigned NumElements = PTy->getNumElements();
604 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
605
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000606 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000607 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
608
609 // Create a VConstant node with generic Vector type.
610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
613 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000614 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
615 return N = DAG.getConstantFP(CFP->getValue(), VT);
616 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
617 unsigned NumElements = PTy->getNumElements();
618 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000619
620 // Now that we know the number and type of the elements, push a
621 // Constant or ConstantFP node onto the ops list for each element of
622 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000623 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000624 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000625 for (unsigned i = 0; i != NumElements; ++i)
626 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000627 } else {
628 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
629 SDOperand Op;
630 if (MVT::isFloatingPoint(PVT))
631 Op = DAG.getConstantFP(0, PVT);
632 else
633 Op = DAG.getConstant(0, PVT);
634 Ops.assign(NumElements, Op);
635 }
636
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000637 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000638 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
639 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000640 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000641 } else {
642 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000643 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000644 }
645 }
646
647 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
648 std::map<const AllocaInst*, int>::iterator SI =
649 FuncInfo.StaticAllocaMap.find(AI);
650 if (SI != FuncInfo.StaticAllocaMap.end())
651 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
652 }
653
654 std::map<const Value*, unsigned>::const_iterator VMI =
655 FuncInfo.ValueMap.find(V);
656 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
657
658 unsigned InReg = VMI->second;
659
660 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000661 if (VT != MVT::Vector) {
662 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000663
Chris Lattner5fe1f542006-03-31 02:06:56 +0000664 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
665 if (DestVT < VT) {
666 // Source must be expanded. This input value is actually coming from the
667 // register pair VMI->second and VMI->second+1.
668 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
669 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
670 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000671 if (MVT::isFloatingPoint(VT))
672 N = DAG.getNode(ISD::FP_ROUND, VT, N);
673 else
674 N = DAG.getNode(ISD::TRUNCATE, VT, N);
675 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000676 } else {
677 // Otherwise, if this is a vector, make it available as a generic vector
678 // here.
679 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000680 const PackedType *PTy = cast<PackedType>(VTy);
681 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000682 PTyLegalElementVT);
683
684 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000685 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000686 if (PTyElementVT == PTyLegalElementVT) {
687 // If the value types are legal, just VBUILD the CopyFromReg nodes.
688 for (unsigned i = 0; i != NE; ++i)
689 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
690 PTyElementVT));
691 } else if (PTyElementVT < PTyLegalElementVT) {
692 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
693 for (unsigned i = 0; i != NE; ++i) {
694 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
695 PTyElementVT);
696 if (MVT::isFloatingPoint(PTyElementVT))
697 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
698 else
699 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
700 Ops.push_back(Op);
701 }
702 } else {
703 // If the register was expanded, use BUILD_PAIR.
704 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
705 for (unsigned i = 0; i != NE/2; ++i) {
706 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT);
708 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT);
710 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
711 }
712 }
713
714 Ops.push_back(DAG.getConstant(NE, MVT::i32));
715 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000716 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000717
718 // Finally, use a VBIT_CONVERT to make this available as the appropriate
719 // vector type.
720 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
721 DAG.getConstant(PTy->getNumElements(),
722 MVT::i32),
723 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000724 }
725
726 return N;
727}
728
729
Chris Lattner7a60d912005-01-07 07:47:53 +0000730void SelectionDAGLowering::visitRet(ReturnInst &I) {
731 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000732 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000733 return;
734 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000735 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000736 NewValues.push_back(getRoot());
737 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
738 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000739 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000740
741 // If this is an integer return value, we need to promote it ourselves to
742 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
743 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000744 // FIXME: C calling convention requires the return type to be promoted to
745 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000746 if (MVT::isInteger(RetOp.getValueType()) &&
747 RetOp.getValueType() < MVT::i64) {
748 MVT::ValueType TmpVT;
749 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
750 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
751 else
752 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000753
Evan Chenga2e99532006-05-26 23:09:09 +0000754 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000755 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
756 else
757 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
758 }
759 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000760 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000761 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000762 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
763 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000764}
765
766void SelectionDAGLowering::visitBr(BranchInst &I) {
767 // Update machine-CFG edges.
768 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000769 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000770
771 // Figure out which block is immediately after the current one.
772 MachineBasicBlock *NextBlock = 0;
773 MachineFunction::iterator BBI = CurMBB;
774 if (++BBI != CurMBB->getParent()->end())
775 NextBlock = BBI;
776
777 if (I.isUnconditional()) {
778 // If this is not a fall-through branch, emit the branch.
779 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000780 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000781 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 } else {
783 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000784 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000785
786 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000787 if (Succ1MBB == NextBlock) {
788 // If the condition is false, fall through. This means we should branch
789 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000790 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000791 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000792 } else if (Succ0MBB == NextBlock) {
793 // If the condition is true, fall through. This means we should branch if
794 // the condition is false to Succ #1. Invert the condition first.
795 SDOperand True = DAG.getConstant(1, Cond.getValueType());
796 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000797 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000798 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000799 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000800 std::vector<SDOperand> Ops;
801 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000802 // If the false case is the current basic block, then this is a self
803 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
804 // adds an extra instruction in the loop. Instead, invert the
805 // condition and emit "Loop: ... br!cond Loop; br Out.
806 if (CurMBB == Succ1MBB) {
807 std::swap(Succ0MBB, Succ1MBB);
808 SDOperand True = DAG.getConstant(1, Cond.getValueType());
809 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
810 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000811 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
812 DAG.getBasicBlock(Succ0MBB));
813 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
814 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000815 }
816 }
817}
818
Nate Begemaned728c12006-03-27 01:32:24 +0000819/// visitSwitchCase - Emits the necessary code to represent a single node in
820/// the binary search tree resulting from lowering a switch instruction.
821void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
822 SDOperand SwitchOp = getValue(CB.SwitchV);
823 SDOperand CaseOp = getValue(CB.CaseC);
824 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
825
826 // Set NextBlock to be the MBB immediately after the current one, if any.
827 // This is used to avoid emitting unnecessary branches to the next block.
828 MachineBasicBlock *NextBlock = 0;
829 MachineFunction::iterator BBI = CurMBB;
830 if (++BBI != CurMBB->getParent()->end())
831 NextBlock = BBI;
832
833 // If the lhs block is the next block, invert the condition so that we can
834 // fall through to the lhs instead of the rhs block.
835 if (CB.LHSBB == NextBlock) {
836 std::swap(CB.LHSBB, CB.RHSBB);
837 SDOperand True = DAG.getConstant(1, Cond.getValueType());
838 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
839 }
840 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
841 DAG.getBasicBlock(CB.LHSBB));
842 if (CB.RHSBB == NextBlock)
843 DAG.setRoot(BrCond);
844 else
845 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
846 DAG.getBasicBlock(CB.RHSBB)));
847 // Update successor info
848 CurMBB->addSuccessor(CB.LHSBB);
849 CurMBB->addSuccessor(CB.RHSBB);
850}
851
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000852void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000853 // Emit the code for the jump table
854 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000855 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
856 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +0000857 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000858 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +0000859 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000860 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
861 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000862 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +0000863 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
864 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +0000865 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000866 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +0000867 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +0000868 // For Pic, the sequence is:
869 // BRIND(load(Jumptable + index) + RelocBase)
870 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +0000871 SDOperand Reloc;
872 if (TLI.usesGlobalOffsetTable())
873 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
874 else
875 Reloc = TAB;
Chris Lattner4c3ef472006-10-22 22:47:10 +0000876 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
877 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman78756502006-07-27 01:13:04 +0000878 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
879 } else {
880 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
881 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000882}
883
Nate Begemaned728c12006-03-27 01:32:24 +0000884void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
885 // Figure out which block is immediately after the current one.
886 MachineBasicBlock *NextBlock = 0;
887 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000888
Nate Begemaned728c12006-03-27 01:32:24 +0000889 if (++BBI != CurMBB->getParent()->end())
890 NextBlock = BBI;
891
Chris Lattner6d6fc262006-10-22 21:36:53 +0000892 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
893
Nate Begemaned728c12006-03-27 01:32:24 +0000894 // If there is only the default destination, branch to it if it is not the
895 // next basic block. Otherwise, just fall through.
896 if (I.getNumOperands() == 2) {
897 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000898
Nate Begemaned728c12006-03-27 01:32:24 +0000899 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +0000900 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +0000901 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +0000902 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000903
Chris Lattner6d6fc262006-10-22 21:36:53 +0000904 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000905 return;
906 }
907
908 // If there are any non-default case statements, create a vector of Cases
909 // representing each one, and sort the vector so that we can efficiently
910 // create a binary search tree from them.
911 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000912
Nate Begemaned728c12006-03-27 01:32:24 +0000913 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
914 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
915 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
916 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000917
Nate Begemaned728c12006-03-27 01:32:24 +0000918 std::sort(Cases.begin(), Cases.end(), CaseCmp());
919
920 // Get the Value to be switched on and default basic blocks, which will be
921 // inserted into CaseBlock records, representing basic blocks in the binary
922 // search tree.
923 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000924
925 // Get the MachineFunction which holds the current MBB. This is used during
926 // emission of jump tables, and when inserting any additional MBBs necessary
927 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +0000928 MachineFunction *CurMF = CurMBB->getParent();
929 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +0000930
931 // If the switch has few cases (two or less) emit a series of specific
932 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +0000933 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +0000934 // TODO: If any two of the cases has the same destination, and if one value
935 // is the same as the other, but has one bit unset that the other has set,
936 // use bit manipulation to do two compares at once. For example:
937 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
938
Chris Lattner4c931502006-10-23 18:38:22 +0000939 // Rearrange the case blocks so that the last one falls through if possible.
940 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
941 // The last case block won't fall through into 'NextBlock' if we emit the
942 // branches in this order. See if rearranging a case value would help.
943 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
944 if (Cases[i].second == NextBlock) {
945 std::swap(Cases[i], Cases.back());
946 break;
947 }
948 }
949 }
950
951
Chris Lattner6d6fc262006-10-22 21:36:53 +0000952 // Create a CaseBlock record representing a conditional branch to
953 // the Case's target mbb if the value being switched on SV is equal
954 // to C.
955 MachineBasicBlock *CurBlock = CurMBB;
956 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
957 MachineBasicBlock *FallThrough;
958 if (i != e-1) {
959 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
960 CurMF->getBasicBlockList().insert(BBI, FallThrough);
961 } else {
962 // If the last case doesn't match, go to the default block.
963 FallThrough = Default;
964 }
965
966 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
967 Cases[i].second, FallThrough, CurBlock);
968
969 // If emitting the first comparison, just call visitSwitchCase to emit the
970 // code into the current block. Otherwise, push the CaseBlock onto the
971 // vector to be later processed by SDISel, and insert the node's MBB
972 // before the next MBB.
973 if (CurBlock == CurMBB)
974 visitSwitchCase(CB);
975 else
976 SwitchCases.push_back(CB);
977
978 CurBlock = FallThrough;
979 }
980 return;
981 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000982
Nate Begemand7a19102006-05-08 16:51:36 +0000983 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
984 // target supports indirect branches, then emit a jump table rather than
985 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +0000986 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +0000987 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000988 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
989 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +0000990 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
991
Nate Begemand7a19102006-05-08 16:51:36 +0000992 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000993 // Create a new basic block to hold the code for loading the address
994 // of the jump table, and jumping to it. Update successor information;
995 // we will either branch to the default case for the switch, or the jump
996 // table.
997 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
998 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
999 CurMBB->addSuccessor(Default);
1000 CurMBB->addSuccessor(JumpTableBB);
1001
1002 // Subtract the lowest switch case value from the value being switched on
1003 // and conditional branch to default mbb if the result is greater than the
1004 // difference between smallest and largest cases.
1005 SDOperand SwitchOp = getValue(SV);
1006 MVT::ValueType VT = SwitchOp.getValueType();
1007 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1008 DAG.getConstant(First, VT));
1009
1010 // The SDNode we just created, which holds the value being switched on
1011 // minus the the smallest case value, needs to be copied to a virtual
1012 // register so it can be used as an index into the jump table in a
1013 // subsequent basic block. This value may be smaller or larger than the
1014 // target's pointer type, and therefore require extension or truncating.
1015 if (VT > TLI.getPointerTy())
1016 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1017 else
1018 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001019
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001020 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1021 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1022
1023 // Emit the range check for the jump table, and branch to the default
1024 // block for the switch statement if the value being switched on exceeds
1025 // the largest case in the switch.
1026 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1027 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1028 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1029 DAG.getBasicBlock(Default)));
1030
Nate Begemandf488392006-05-03 03:48:02 +00001031 // Build a vector of destination BBs, corresponding to each target
1032 // of the jump table. If the value of the jump table slot corresponds to
1033 // a case statement, push the case's BB onto the vector, otherwise, push
1034 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001035 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001036 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001037 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001038 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001039 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001040 ++ii;
1041 } else {
1042 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001043 }
Nate Begemandf488392006-05-03 03:48:02 +00001044
1045 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001046 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1047 E = DestBBs.end(); I != E; ++I)
1048 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +00001049
1050 // Create a jump table index for this jump table, or return an existing
1051 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001052 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1053
1054 // Set the jump table information so that we can codegen it as a second
1055 // MachineBasicBlock
1056 JT.Reg = JumpTableReg;
1057 JT.JTI = JTI;
1058 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001059 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001060 return;
1061 }
1062 }
Nate Begemaned728c12006-03-27 01:32:24 +00001063
1064 // Push the initial CaseRec onto the worklist
1065 std::vector<CaseRec> CaseVec;
1066 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1067
1068 while (!CaseVec.empty()) {
1069 // Grab a record representing a case range to process off the worklist
1070 CaseRec CR = CaseVec.back();
1071 CaseVec.pop_back();
1072
1073 // Size is the number of Cases represented by this range. If Size is 1,
1074 // then we are processing a leaf of the binary search tree. Otherwise,
1075 // we need to pick a pivot, and push left and right ranges onto the
1076 // worklist.
1077 unsigned Size = CR.Range.second - CR.Range.first;
1078
1079 if (Size == 1) {
1080 // Create a CaseBlock record representing a conditional branch to
1081 // the Case's target mbb if the value being switched on SV is equal
1082 // to C. Otherwise, branch to default.
1083 Constant *C = CR.Range.first->first;
1084 MachineBasicBlock *Target = CR.Range.first->second;
1085 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1086 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001087
Nate Begemaned728c12006-03-27 01:32:24 +00001088 // If the MBB representing the leaf node is the current MBB, then just
1089 // call visitSwitchCase to emit the code into the current block.
1090 // Otherwise, push the CaseBlock onto the vector to be later processed
1091 // by SDISel, and insert the node's MBB before the next MBB.
1092 if (CR.CaseBB == CurMBB)
1093 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001094 else
Nate Begemaned728c12006-03-27 01:32:24 +00001095 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001096 } else {
1097 // split case range at pivot
1098 CaseItr Pivot = CR.Range.first + (Size / 2);
1099 CaseRange LHSR(CR.Range.first, Pivot);
1100 CaseRange RHSR(Pivot, CR.Range.second);
1101 Constant *C = Pivot->first;
1102 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001103
Nate Begemaned728c12006-03-27 01:32:24 +00001104 // We know that we branch to the LHS if the Value being switched on is
1105 // less than the Pivot value, C. We use this to optimize our binary
1106 // tree a bit, by recognizing that if SV is greater than or equal to the
1107 // LHS's Case Value, and that Case Value is exactly one less than the
1108 // Pivot's Value, then we can branch directly to the LHS's Target,
1109 // rather than creating a leaf node for it.
1110 if ((LHSR.second - LHSR.first) == 1 &&
1111 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001112 cast<ConstantIntegral>(C)->getZExtValue() ==
1113 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001114 LHSBB = LHSR.first->second;
1115 } else {
1116 LHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001117 CurMF->getBasicBlockList().insert(BBI, LHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001118 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1119 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001120
Nate Begemaned728c12006-03-27 01:32:24 +00001121 // Similar to the optimization above, if the Value being switched on is
1122 // known to be less than the Constant CR.LT, and the current Case Value
1123 // is CR.LT - 1, then we can branch directly to the target block for
1124 // the current Case Value, rather than emitting a RHS leaf node for it.
1125 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001126 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1127 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001128 RHSBB = RHSR.first->second;
1129 } else {
1130 RHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001131 CurMF->getBasicBlockList().insert(BBI, RHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001132 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1133 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001134
Nate Begemaned728c12006-03-27 01:32:24 +00001135 // Create a CaseBlock record representing a conditional branch to
1136 // the LHS node if the value being switched on SV is less than C.
1137 // Otherwise, branch to LHS.
1138 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1139 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001140
Nate Begemaned728c12006-03-27 01:32:24 +00001141 if (CR.CaseBB == CurMBB)
1142 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001143 else
Nate Begemaned728c12006-03-27 01:32:24 +00001144 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001145 }
1146 }
1147}
1148
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001149void SelectionDAGLowering::visitSub(User &I) {
1150 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001151 if (I.getType()->isFloatingPoint()) {
1152 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1153 if (CFP->isExactlyValue(-0.0)) {
1154 SDOperand Op2 = getValue(I.getOperand(1));
1155 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1156 return;
1157 }
Chris Lattner6f3b5772005-09-28 22:28:18 +00001158 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001159 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001160}
1161
Nate Begemanb2e089c2005-11-19 00:36:38 +00001162void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1163 unsigned VecOp) {
1164 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001165 SDOperand Op1 = getValue(I.getOperand(0));
1166 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001167
Chris Lattner19baba62005-11-19 18:40:42 +00001168 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001169 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1170 } else if (Ty->isFloatingPoint()) {
1171 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1172 } else {
1173 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +00001174 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1175 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1176 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001177 }
Nate Begeman127321b2005-11-18 07:42:56 +00001178}
Chris Lattner96c26752005-01-19 22:31:21 +00001179
Nate Begeman127321b2005-11-18 07:42:56 +00001180void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1181 SDOperand Op1 = getValue(I.getOperand(0));
1182 SDOperand Op2 = getValue(I.getOperand(1));
1183
1184 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1185
Chris Lattner7a60d912005-01-07 07:47:53 +00001186 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1187}
1188
1189void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001190 ISD::CondCode UnsignedOpcode,
1191 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001192 SDOperand Op1 = getValue(I.getOperand(0));
1193 SDOperand Op2 = getValue(I.getOperand(1));
1194 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001195 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001196 Opcode = FPOpcode;
1197 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001198 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001199 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001200}
1201
1202void SelectionDAGLowering::visitSelect(User &I) {
1203 SDOperand Cond = getValue(I.getOperand(0));
1204 SDOperand TrueVal = getValue(I.getOperand(1));
1205 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001206 if (!isa<PackedType>(I.getType())) {
1207 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1208 TrueVal, FalseVal));
1209 } else {
1210 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1211 *(TrueVal.Val->op_end()-2),
1212 *(TrueVal.Val->op_end()-1)));
1213 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001214}
1215
1216void SelectionDAGLowering::visitCast(User &I) {
1217 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001218 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001219 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001220
Chris Lattner2f4119a2006-03-22 20:09:35 +00001221 if (DestVT == MVT::Vector) {
1222 // This is a cast to a vector from something else. This is always a bit
1223 // convert. Get information about the input vector.
1224 const PackedType *DestTy = cast<PackedType>(I.getType());
1225 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1226 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1227 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1228 DAG.getValueType(EltVT)));
1229 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001230 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001231 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001232 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001233 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001234 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001235 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001236 } else if (isInteger(SrcVT)) {
1237 if (isInteger(DestVT)) { // Int -> Int cast
1238 if (DestVT < SrcVT) // Truncating cast?
1239 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001240 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001241 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001242 else
Chris Lattner4024c002006-03-15 22:19:46 +00001243 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001244 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001245 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001246 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001247 else
Chris Lattner4024c002006-03-15 22:19:46 +00001248 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001249 } else {
1250 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001251 }
Chris Lattner4024c002006-03-15 22:19:46 +00001252 } else if (isFloatingPoint(SrcVT)) {
1253 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1254 if (DestVT < SrcVT) // Rounding cast?
1255 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001256 else
Chris Lattner4024c002006-03-15 22:19:46 +00001257 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001258 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001259 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001260 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001261 else
Chris Lattner4024c002006-03-15 22:19:46 +00001262 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001263 } else {
1264 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001265 }
1266 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001267 assert(SrcVT == MVT::Vector && "Unknown cast!");
1268 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1269 // This is a cast from a vector to something else. This is always a bit
1270 // convert. Get information about the input vector.
1271 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001272 }
1273}
1274
Chris Lattner67271862006-03-29 00:11:43 +00001275void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001276 SDOperand InVec = getValue(I.getOperand(0));
1277 SDOperand InVal = getValue(I.getOperand(1));
1278 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1279 getValue(I.getOperand(2)));
1280
Chris Lattner29b23012006-03-19 01:17:20 +00001281 SDOperand Num = *(InVec.Val->op_end()-2);
1282 SDOperand Typ = *(InVec.Val->op_end()-1);
1283 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1284 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001285}
1286
Chris Lattner67271862006-03-29 00:11:43 +00001287void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001288 SDOperand InVec = getValue(I.getOperand(0));
1289 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1290 getValue(I.getOperand(1)));
1291 SDOperand Typ = *(InVec.Val->op_end()-1);
1292 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1293 TLI.getValueType(I.getType()), InVec, InIdx));
1294}
Chris Lattner32206f52006-03-18 01:44:44 +00001295
Chris Lattner098c01e2006-04-08 04:15:24 +00001296void SelectionDAGLowering::visitShuffleVector(User &I) {
1297 SDOperand V1 = getValue(I.getOperand(0));
1298 SDOperand V2 = getValue(I.getOperand(1));
1299 SDOperand Mask = getValue(I.getOperand(2));
1300
1301 SDOperand Num = *(V1.Val->op_end()-2);
1302 SDOperand Typ = *(V2.Val->op_end()-1);
1303 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1304 V1, V2, Mask, Num, Typ));
1305}
1306
1307
Chris Lattner7a60d912005-01-07 07:47:53 +00001308void SelectionDAGLowering::visitGetElementPtr(User &I) {
1309 SDOperand N = getValue(I.getOperand(0));
1310 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001311
1312 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1313 OI != E; ++OI) {
1314 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001315 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001316 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001317 if (Field) {
1318 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001319 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001320 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001321 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001322 }
1323 Ty = StTy->getElementType(Field);
1324 } else {
1325 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001326
Chris Lattner43535a12005-11-09 04:45:33 +00001327 // If this is a constant subscript, handle it quickly.
1328 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001329 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001330 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001331 if (CI->getType()->isSigned())
1332 Offs = (int64_t)
1333 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001334 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001335 Offs =
1336 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001337 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1338 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001339 }
Chris Lattner43535a12005-11-09 04:45:33 +00001340
1341 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001342 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001343 SDOperand IdxN = getValue(Idx);
1344
1345 // If the index is smaller or larger than intptr_t, truncate or extend
1346 // it.
1347 if (IdxN.getValueType() < N.getValueType()) {
1348 if (Idx->getType()->isSigned())
1349 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1350 else
1351 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1352 } else if (IdxN.getValueType() > N.getValueType())
1353 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1354
1355 // If this is a multiply by a power of two, turn it into a shl
1356 // immediately. This is a very common case.
1357 if (isPowerOf2_64(ElementSize)) {
1358 unsigned Amt = Log2_64(ElementSize);
1359 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001360 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001361 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1362 continue;
1363 }
1364
1365 SDOperand Scale = getIntPtrConstant(ElementSize);
1366 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1367 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001368 }
1369 }
1370 setValue(&I, N);
1371}
1372
1373void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1374 // If this is a fixed sized alloca in the entry block of the function,
1375 // allocate it statically on the stack.
1376 if (FuncInfo.StaticAllocaMap.count(&I))
1377 return; // getValue will auto-populate this.
1378
1379 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001380 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1381 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001382 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001383
1384 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001385 MVT::ValueType IntPtr = TLI.getPointerTy();
1386 if (IntPtr < AllocSize.getValueType())
1387 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1388 else if (IntPtr > AllocSize.getValueType())
1389 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001390
Chris Lattnereccb73d2005-01-22 23:04:37 +00001391 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001392 getIntPtrConstant(TySize));
1393
1394 // Handle alignment. If the requested alignment is less than or equal to the
1395 // stack alignment, ignore it and round the size of the allocation up to the
1396 // stack alignment size. If the size is greater than the stack alignment, we
1397 // note this in the DYNAMIC_STACKALLOC node.
1398 unsigned StackAlign =
1399 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1400 if (Align <= StackAlign) {
1401 Align = 0;
1402 // Add SA-1 to the size.
1403 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1404 getIntPtrConstant(StackAlign-1));
1405 // Mask out the low bits for alignment purposes.
1406 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1407 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1408 }
1409
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001410 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001411 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1412 MVT::Other);
1413 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001414 DAG.setRoot(setValue(&I, DSA).getValue(1));
1415
1416 // Inform the Frame Information that we have just allocated a variable-sized
1417 // object.
1418 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1419}
1420
Chris Lattner7a60d912005-01-07 07:47:53 +00001421void SelectionDAGLowering::visitLoad(LoadInst &I) {
1422 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001423
Chris Lattner4d9651c2005-01-17 22:19:26 +00001424 SDOperand Root;
1425 if (I.isVolatile())
1426 Root = getRoot();
1427 else {
1428 // Do not serialize non-volatile loads against each other.
1429 Root = DAG.getRoot();
1430 }
Chris Lattner4024c002006-03-15 22:19:46 +00001431
Evan Chenge71fe34d2006-10-09 20:57:25 +00001432 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001433 Root, I.isVolatile()));
1434}
1435
1436SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001437 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001438 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001439 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001440 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001441 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001442 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1443 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001444 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001445 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001446 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001447
Chris Lattner4024c002006-03-15 22:19:46 +00001448 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001449 DAG.setRoot(L.getValue(1));
1450 else
1451 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001452
1453 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001454}
1455
1456
1457void SelectionDAGLowering::visitStore(StoreInst &I) {
1458 Value *SrcV = I.getOperand(0);
1459 SDOperand Src = getValue(SrcV);
1460 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001461 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1462 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001463}
1464
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001465/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1466/// access memory and has no other side effects at all.
1467static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1468#define GET_NO_MEMORY_INTRINSICS
1469#include "llvm/Intrinsics.gen"
1470#undef GET_NO_MEMORY_INTRINSICS
1471 return false;
1472}
1473
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001474// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1475// have any side-effects or if it only reads memory.
1476static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1477#define GET_SIDE_EFFECT_INFO
1478#include "llvm/Intrinsics.gen"
1479#undef GET_SIDE_EFFECT_INFO
1480 return false;
1481}
1482
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001483/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1484/// node.
1485void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1486 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001487 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001488 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001489
1490 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001491 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001492 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1493 if (OnlyLoad) {
1494 // We don't need to serialize loads against other loads.
1495 Ops.push_back(DAG.getRoot());
1496 } else {
1497 Ops.push_back(getRoot());
1498 }
1499 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001500
1501 // Add the intrinsic ID as an integer operand.
1502 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1503
1504 // Add all operands of the call to the operand list.
1505 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1506 SDOperand Op = getValue(I.getOperand(i));
1507
1508 // If this is a vector type, force it to the right packed type.
1509 if (Op.getValueType() == MVT::Vector) {
1510 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1511 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1512
1513 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1514 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1515 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1516 }
1517
1518 assert(TLI.isTypeLegal(Op.getValueType()) &&
1519 "Intrinsic uses a non-legal type?");
1520 Ops.push_back(Op);
1521 }
1522
1523 std::vector<MVT::ValueType> VTs;
1524 if (I.getType() != Type::VoidTy) {
1525 MVT::ValueType VT = TLI.getValueType(I.getType());
1526 if (VT == MVT::Vector) {
1527 const PackedType *DestTy = cast<PackedType>(I.getType());
1528 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1529
1530 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1531 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1532 }
1533
1534 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1535 VTs.push_back(VT);
1536 }
1537 if (HasChain)
1538 VTs.push_back(MVT::Other);
1539
Chris Lattnerbd887772006-08-14 23:53:35 +00001540 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1541
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001542 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001543 SDOperand Result;
1544 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001545 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1546 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001547 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001548 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1549 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001550 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001551 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1552 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001553
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001554 if (HasChain) {
1555 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1556 if (OnlyLoad)
1557 PendingLoads.push_back(Chain);
1558 else
1559 DAG.setRoot(Chain);
1560 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001561 if (I.getType() != Type::VoidTy) {
1562 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1563 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1564 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1565 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1566 DAG.getValueType(EVT));
1567 }
1568 setValue(&I, Result);
1569 }
1570}
1571
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001572/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1573/// we want to emit this as a call to a named external function, return the name
1574/// otherwise lower it and return null.
1575const char *
1576SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1577 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001578 default:
1579 // By default, turn this into a target intrinsic node.
1580 visitTargetIntrinsic(I, Intrinsic);
1581 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001582 case Intrinsic::vastart: visitVAStart(I); return 0;
1583 case Intrinsic::vaend: visitVAEnd(I); return 0;
1584 case Intrinsic::vacopy: visitVACopy(I); return 0;
1585 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1586 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1587 case Intrinsic::setjmp:
1588 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1589 break;
1590 case Intrinsic::longjmp:
1591 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1592 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001593 case Intrinsic::memcpy_i32:
1594 case Intrinsic::memcpy_i64:
1595 visitMemIntrinsic(I, ISD::MEMCPY);
1596 return 0;
1597 case Intrinsic::memset_i32:
1598 case Intrinsic::memset_i64:
1599 visitMemIntrinsic(I, ISD::MEMSET);
1600 return 0;
1601 case Intrinsic::memmove_i32:
1602 case Intrinsic::memmove_i64:
1603 visitMemIntrinsic(I, ISD::MEMMOVE);
1604 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001605
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001606 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001607 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001608 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001609 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001610 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001611
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001612 Ops[0] = getRoot();
1613 Ops[1] = getValue(SPI.getLineValue());
1614 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001615
Jim Laskeya8bdac82006-03-23 18:06:46 +00001616 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001617 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001618 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1619
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001620 Ops[3] = DAG.getString(CompileUnit->getFileName());
1621 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001622
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001623 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001624 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001625
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001626 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001627 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001628 case Intrinsic::dbg_region_start: {
1629 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1630 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001631 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001632 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001633 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1634 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001635 }
1636
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001637 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001638 }
1639 case Intrinsic::dbg_region_end: {
1640 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1641 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001642 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001643 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001644 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1645 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001646 }
1647
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001648 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001649 }
1650 case Intrinsic::dbg_func_start: {
1651 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1652 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001653 if (DebugInfo && FSI.getSubprogram() &&
1654 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001655 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001656 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1657 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001658 }
1659
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001660 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001661 }
1662 case Intrinsic::dbg_declare: {
1663 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1664 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001665 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001666 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001667 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001668 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001669 }
1670
1671 return 0;
1672 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001673
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001674 case Intrinsic::isunordered_f32:
1675 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001676 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1677 getValue(I.getOperand(2)), ISD::SETUO));
1678 return 0;
1679
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001680 case Intrinsic::sqrt_f32:
1681 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001682 setValue(&I, DAG.getNode(ISD::FSQRT,
1683 getValue(I.getOperand(1)).getValueType(),
1684 getValue(I.getOperand(1))));
1685 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001686 case Intrinsic::powi_f32:
1687 case Intrinsic::powi_f64:
1688 setValue(&I, DAG.getNode(ISD::FPOWI,
1689 getValue(I.getOperand(1)).getValueType(),
1690 getValue(I.getOperand(1)),
1691 getValue(I.getOperand(2))));
1692 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001693 case Intrinsic::pcmarker: {
1694 SDOperand Tmp = getValue(I.getOperand(1));
1695 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1696 return 0;
1697 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001698 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001699 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001700 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1701 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1702 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001703 setValue(&I, Tmp);
1704 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001705 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001706 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001707 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001708 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001709 case Intrinsic::bswap_i64:
1710 setValue(&I, DAG.getNode(ISD::BSWAP,
1711 getValue(I.getOperand(1)).getValueType(),
1712 getValue(I.getOperand(1))));
1713 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001714 case Intrinsic::cttz_i8:
1715 case Intrinsic::cttz_i16:
1716 case Intrinsic::cttz_i32:
1717 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001718 setValue(&I, DAG.getNode(ISD::CTTZ,
1719 getValue(I.getOperand(1)).getValueType(),
1720 getValue(I.getOperand(1))));
1721 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001722 case Intrinsic::ctlz_i8:
1723 case Intrinsic::ctlz_i16:
1724 case Intrinsic::ctlz_i32:
1725 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001726 setValue(&I, DAG.getNode(ISD::CTLZ,
1727 getValue(I.getOperand(1)).getValueType(),
1728 getValue(I.getOperand(1))));
1729 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001730 case Intrinsic::ctpop_i8:
1731 case Intrinsic::ctpop_i16:
1732 case Intrinsic::ctpop_i32:
1733 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001734 setValue(&I, DAG.getNode(ISD::CTPOP,
1735 getValue(I.getOperand(1)).getValueType(),
1736 getValue(I.getOperand(1))));
1737 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001738 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001739 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001740 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1741 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001742 setValue(&I, Tmp);
1743 DAG.setRoot(Tmp.getValue(1));
1744 return 0;
1745 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001746 case Intrinsic::stackrestore: {
1747 SDOperand Tmp = getValue(I.getOperand(1));
1748 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001749 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001750 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001751 case Intrinsic::prefetch:
1752 // FIXME: Currently discarding prefetches.
1753 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001754 }
1755}
1756
1757
Chris Lattner7a60d912005-01-07 07:47:53 +00001758void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001759 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001760 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001761 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001762 if (unsigned IID = F->getIntrinsicID()) {
1763 RenameFn = visitIntrinsicCall(I, IID);
1764 if (!RenameFn)
1765 return;
1766 } else { // Not an LLVM intrinsic.
1767 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001768 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1769 if (I.getNumOperands() == 3 && // Basic sanity checks.
1770 I.getOperand(1)->getType()->isFloatingPoint() &&
1771 I.getType() == I.getOperand(1)->getType() &&
1772 I.getType() == I.getOperand(2)->getType()) {
1773 SDOperand LHS = getValue(I.getOperand(1));
1774 SDOperand RHS = getValue(I.getOperand(2));
1775 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1776 LHS, RHS));
1777 return;
1778 }
1779 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001780 if (I.getNumOperands() == 2 && // Basic sanity checks.
1781 I.getOperand(1)->getType()->isFloatingPoint() &&
1782 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001783 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001784 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1785 return;
1786 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001787 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001788 if (I.getNumOperands() == 2 && // Basic sanity checks.
1789 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001790 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001791 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001792 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1793 return;
1794 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001795 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001796 if (I.getNumOperands() == 2 && // Basic sanity checks.
1797 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001798 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001799 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001800 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1801 return;
1802 }
1803 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001804 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001805 } else if (isa<InlineAsm>(I.getOperand(0))) {
1806 visitInlineAsm(I);
1807 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001808 }
Misha Brukman835702a2005-04-21 22:36:52 +00001809
Chris Lattner18d2b342005-01-08 22:48:57 +00001810 SDOperand Callee;
1811 if (!RenameFn)
1812 Callee = getValue(I.getOperand(0));
1813 else
1814 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001815 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001816 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001817 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1818 Value *Arg = I.getOperand(i);
1819 SDOperand ArgNode = getValue(Arg);
1820 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1821 }
Misha Brukman835702a2005-04-21 22:36:52 +00001822
Nate Begemanf6565252005-03-26 01:29:23 +00001823 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1824 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001825
Chris Lattner1f45cd72005-01-08 19:26:18 +00001826 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001827 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001828 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001829 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001830 setValue(&I, Result.first);
1831 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001832}
1833
Chris Lattner6f87d182006-02-22 22:37:12 +00001834SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001835 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001836 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1837 Chain = Val.getValue(1);
1838 Flag = Val.getValue(2);
1839
1840 // If the result was expanded, copy from the top part.
1841 if (Regs.size() > 1) {
1842 assert(Regs.size() == 2 &&
1843 "Cannot expand to more than 2 elts yet!");
1844 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00001845 Chain = Hi.getValue(1);
1846 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001847 if (DAG.getTargetLoweringInfo().isLittleEndian())
1848 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1849 else
1850 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001851 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001852
Chris Lattner705948d2006-06-08 18:22:48 +00001853 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00001854 // appropriate type.
1855 if (RegVT == ValueVT)
1856 return Val;
1857
Chris Lattner705948d2006-06-08 18:22:48 +00001858 if (MVT::isInteger(RegVT)) {
1859 if (ValueVT < RegVT)
1860 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1861 else
1862 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1863 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001864 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00001865 }
Chris Lattner6f87d182006-02-22 22:37:12 +00001866}
1867
Chris Lattner571d9642006-02-23 19:21:04 +00001868/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1869/// specified value into the registers specified by this object. This uses
1870/// Chain/Flag as the input and updates them for the output Chain/Flag.
1871void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00001872 SDOperand &Chain, SDOperand &Flag,
1873 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001874 if (Regs.size() == 1) {
1875 // If there is a single register and the types differ, this must be
1876 // a promotion.
1877 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00001878 if (MVT::isInteger(RegVT)) {
1879 if (RegVT < ValueVT)
1880 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1881 else
1882 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1883 } else
Chris Lattner571d9642006-02-23 19:21:04 +00001884 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1885 }
1886 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1887 Flag = Chain.getValue(1);
1888 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001889 std::vector<unsigned> R(Regs);
1890 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1891 std::reverse(R.begin(), R.end());
1892
1893 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001894 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00001895 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001896 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001897 Flag = Chain.getValue(1);
1898 }
1899 }
1900}
Chris Lattner6f87d182006-02-22 22:37:12 +00001901
Chris Lattner571d9642006-02-23 19:21:04 +00001902/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1903/// operand list. This adds the code marker and includes the number of
1904/// values added into it.
1905void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001906 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001907 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1908 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1909 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1910}
Chris Lattner6f87d182006-02-22 22:37:12 +00001911
1912/// isAllocatableRegister - If the specified register is safe to allocate,
1913/// i.e. it isn't a stack pointer or some other special register, return the
1914/// register class for the register. Otherwise, return null.
1915static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001916isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1917 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001918 MVT::ValueType FoundVT = MVT::Other;
1919 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001920 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1921 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001922 MVT::ValueType ThisVT = MVT::Other;
1923
Chris Lattnerb1124f32006-02-22 23:09:03 +00001924 const TargetRegisterClass *RC = *RCI;
1925 // If none of the the value types for this register class are valid, we
1926 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001927 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1928 I != E; ++I) {
1929 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001930 // If we have already found this register in a different register class,
1931 // choose the one with the largest VT specified. For example, on
1932 // PowerPC, we favor f64 register classes over f32.
1933 if (FoundVT == MVT::Other ||
1934 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1935 ThisVT = *I;
1936 break;
1937 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001938 }
1939 }
1940
Chris Lattnerbec582f2006-04-02 00:24:45 +00001941 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001942
Chris Lattner6f87d182006-02-22 22:37:12 +00001943 // NOTE: This isn't ideal. In particular, this might allocate the
1944 // frame pointer in functions that need it (due to them not being taken
1945 // out of allocation, because a variable sized allocation hasn't been seen
1946 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001947 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1948 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001949 if (*I == Reg) {
1950 // We found a matching register class. Keep looking at others in case
1951 // we find one with larger registers that this physreg is also in.
1952 FoundRC = RC;
1953 FoundVT = ThisVT;
1954 break;
1955 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001956 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001957 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001958}
1959
1960RegsForValue SelectionDAGLowering::
1961GetRegistersForValue(const std::string &ConstrCode,
1962 MVT::ValueType VT, bool isOutReg, bool isInReg,
1963 std::set<unsigned> &OutputRegs,
1964 std::set<unsigned> &InputRegs) {
1965 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1966 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1967 std::vector<unsigned> Regs;
1968
1969 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1970 MVT::ValueType RegVT;
1971 MVT::ValueType ValueVT = VT;
1972
1973 if (PhysReg.first) {
1974 if (VT == MVT::Other)
1975 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00001976
1977 // Get the actual register value type. This is important, because the user
1978 // may have asked for (e.g.) the AX register in i32 type. We need to
1979 // remember that AX is actually i16 to get the right extension.
1980 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00001981
1982 // This is a explicit reference to a physical register.
1983 Regs.push_back(PhysReg.first);
1984
1985 // If this is an expanded reference, add the rest of the regs to Regs.
1986 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001987 TargetRegisterClass::iterator I = PhysReg.second->begin();
1988 TargetRegisterClass::iterator E = PhysReg.second->end();
1989 for (; *I != PhysReg.first; ++I)
1990 assert(I != E && "Didn't find reg!");
1991
1992 // Already added the first reg.
1993 --NumRegs; ++I;
1994 for (; NumRegs; --NumRegs, ++I) {
1995 assert(I != E && "Ran out of registers to allocate!");
1996 Regs.push_back(*I);
1997 }
1998 }
1999 return RegsForValue(Regs, RegVT, ValueVT);
2000 }
2001
2002 // This is a reference to a register class. Allocate NumRegs consecutive,
2003 // available, registers from the class.
2004 std::vector<unsigned> RegClassRegs =
2005 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2006
2007 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2008 MachineFunction &MF = *CurMBB->getParent();
2009 unsigned NumAllocated = 0;
2010 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2011 unsigned Reg = RegClassRegs[i];
2012 // See if this register is available.
2013 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2014 (isInReg && InputRegs.count(Reg))) { // Already used.
2015 // Make sure we find consecutive registers.
2016 NumAllocated = 0;
2017 continue;
2018 }
2019
2020 // Check to see if this register is allocatable (i.e. don't give out the
2021 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002022 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002023 if (!RC) {
2024 // Make sure we find consecutive registers.
2025 NumAllocated = 0;
2026 continue;
2027 }
2028
2029 // Okay, this register is good, we can use it.
2030 ++NumAllocated;
2031
2032 // If we allocated enough consecutive
2033 if (NumAllocated == NumRegs) {
2034 unsigned RegStart = (i-NumAllocated)+1;
2035 unsigned RegEnd = i+1;
2036 // Mark all of the allocated registers used.
2037 for (unsigned i = RegStart; i != RegEnd; ++i) {
2038 unsigned Reg = RegClassRegs[i];
2039 Regs.push_back(Reg);
2040 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2041 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2042 }
2043
2044 return RegsForValue(Regs, *RC->vt_begin(), VT);
2045 }
2046 }
2047
2048 // Otherwise, we couldn't allocate enough registers for this.
2049 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002050}
2051
Chris Lattner6f87d182006-02-22 22:37:12 +00002052
Chris Lattner476e67b2006-01-26 22:24:51 +00002053/// visitInlineAsm - Handle a call to an InlineAsm object.
2054///
2055void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2056 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2057
2058 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2059 MVT::Other);
2060
2061 // Note, we treat inline asms both with and without side-effects as the same.
2062 // If an inline asm doesn't have side effects and doesn't access memory, we
2063 // could not choose to not chain it.
2064 bool hasSideEffects = IA->hasSideEffects();
2065
Chris Lattner3a5ed552006-02-01 01:28:23 +00002066 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002067 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002068
2069 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2070 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2071 /// if it is a def of that register.
2072 std::vector<SDOperand> AsmNodeOperands;
2073 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2074 AsmNodeOperands.push_back(AsmStr);
2075
2076 SDOperand Chain = getRoot();
2077 SDOperand Flag;
2078
Chris Lattner1558fc62006-02-01 18:59:47 +00002079 // We fully assign registers here at isel time. This is not optimal, but
2080 // should work. For register classes that correspond to LLVM classes, we
2081 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2082 // over the constraints, collecting fixed registers that we know we can't use.
2083 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002084 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002085 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2086 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2087 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002088
Chris Lattner7ad77df2006-02-22 00:56:39 +00002089 MVT::ValueType OpVT;
2090
2091 // Compute the value type for each operand and add it to ConstraintVTs.
2092 switch (Constraints[i].Type) {
2093 case InlineAsm::isOutput:
2094 if (!Constraints[i].isIndirectOutput) {
2095 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2096 OpVT = TLI.getValueType(I.getType());
2097 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002098 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002099 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2100 OpNum++; // Consumes a call operand.
2101 }
2102 break;
2103 case InlineAsm::isInput:
2104 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2105 OpNum++; // Consumes a call operand.
2106 break;
2107 case InlineAsm::isClobber:
2108 OpVT = MVT::Other;
2109 break;
2110 }
2111
2112 ConstraintVTs.push_back(OpVT);
2113
Chris Lattner6f87d182006-02-22 22:37:12 +00002114 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2115 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002116
Chris Lattner6f87d182006-02-22 22:37:12 +00002117 // Build a list of regs that this operand uses. This always has a single
2118 // element for promoted/expanded operands.
2119 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2120 false, false,
2121 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002122
2123 switch (Constraints[i].Type) {
2124 case InlineAsm::isOutput:
2125 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002126 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002127 // If this is an early-clobber output, it cannot be assigned to the same
2128 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002129 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002130 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002131 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002132 case InlineAsm::isInput:
2133 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002134 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002135 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002136 case InlineAsm::isClobber:
2137 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002138 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2139 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002140 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002141 }
2142 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002143
Chris Lattner5c79f982006-02-21 23:12:12 +00002144 // Loop over all of the inputs, copying the operand values into the
2145 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002146 RegsForValue RetValRegs;
2147 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002148 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002149
Chris Lattner2e56e892006-01-31 02:03:41 +00002150 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002151 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2152 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002153
Chris Lattner3a5ed552006-02-01 01:28:23 +00002154 switch (Constraints[i].Type) {
2155 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002156 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2157 if (ConstraintCode.size() == 1) // not a physreg name.
2158 CTy = TLI.getConstraintType(ConstraintCode[0]);
2159
2160 if (CTy == TargetLowering::C_Memory) {
2161 // Memory output.
2162 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2163
2164 // Check that the operand (the address to store to) isn't a float.
2165 if (!MVT::isInteger(InOperandVal.getValueType()))
2166 assert(0 && "MATCH FAIL!");
2167
2168 if (!Constraints[i].isIndirectOutput)
2169 assert(0 && "MATCH FAIL!");
2170
2171 OpNum++; // Consumes a call operand.
2172
2173 // Extend/truncate to the right pointer type if needed.
2174 MVT::ValueType PtrType = TLI.getPointerTy();
2175 if (InOperandVal.getValueType() < PtrType)
2176 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2177 else if (InOperandVal.getValueType() > PtrType)
2178 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2179
2180 // Add information to the INLINEASM node to know about this output.
2181 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2182 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2183 AsmNodeOperands.push_back(InOperandVal);
2184 break;
2185 }
2186
2187 // Otherwise, this is a register output.
2188 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2189
Chris Lattner6f87d182006-02-22 22:37:12 +00002190 // If this is an early-clobber output, or if there is an input
2191 // constraint that matches this, we need to reserve the input register
2192 // so no other inputs allocate to it.
2193 bool UsesInputRegister = false;
2194 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2195 UsesInputRegister = true;
2196
2197 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002198 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002199 RegsForValue Regs =
2200 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2201 true, UsesInputRegister,
2202 OutputRegs, InputRegs);
2203 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002204
Chris Lattner3a5ed552006-02-01 01:28:23 +00002205 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002206 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002207 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002208 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002209 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002210 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002211 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2212 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002213 OpNum++; // Consumes a call operand.
2214 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002215
2216 // Add information to the INLINEASM node to know that this register is
2217 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002218 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002219 break;
2220 }
2221 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002222 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002223 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002224
Chris Lattner7f5880b2006-02-02 00:25:23 +00002225 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2226 // If this is required to match an output register we have already set,
2227 // just use its register.
2228 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002229
Chris Lattner571d9642006-02-23 19:21:04 +00002230 // Scan until we find the definition we already emitted of this operand.
2231 // When we find it, create a RegsForValue operand.
2232 unsigned CurOp = 2; // The first operand.
2233 for (; OperandNo; --OperandNo) {
2234 // Advance to the next operand.
2235 unsigned NumOps =
2236 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002237 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2238 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002239 "Skipped past definitions?");
2240 CurOp += (NumOps>>3)+1;
2241 }
2242
2243 unsigned NumOps =
2244 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2245 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2246 "Skipped past definitions?");
2247
2248 // Add NumOps>>3 registers to MatchedRegs.
2249 RegsForValue MatchedRegs;
2250 MatchedRegs.ValueVT = InOperandVal.getValueType();
2251 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2252 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2253 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2254 MatchedRegs.Regs.push_back(Reg);
2255 }
2256
2257 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002258 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2259 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002260 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002261 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002262 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002263
2264 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2265 if (ConstraintCode.size() == 1) // not a physreg name.
2266 CTy = TLI.getConstraintType(ConstraintCode[0]);
2267
2268 if (CTy == TargetLowering::C_Other) {
2269 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2270 assert(0 && "MATCH FAIL!");
2271
2272 // Add information to the INLINEASM node to know about this input.
2273 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2274 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2275 AsmNodeOperands.push_back(InOperandVal);
2276 break;
2277 } else if (CTy == TargetLowering::C_Memory) {
2278 // Memory input.
2279
2280 // Check that the operand isn't a float.
2281 if (!MVT::isInteger(InOperandVal.getValueType()))
2282 assert(0 && "MATCH FAIL!");
2283
2284 // Extend/truncate to the right pointer type if needed.
2285 MVT::ValueType PtrType = TLI.getPointerTy();
2286 if (InOperandVal.getValueType() < PtrType)
2287 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2288 else if (InOperandVal.getValueType() > PtrType)
2289 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2290
2291 // Add information to the INLINEASM node to know about this input.
2292 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2293 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2294 AsmNodeOperands.push_back(InOperandVal);
2295 break;
2296 }
2297
2298 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2299
2300 // Copy the input into the appropriate registers.
2301 RegsForValue InRegs =
2302 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2303 false, true, OutputRegs, InputRegs);
2304 // FIXME: should be match fail.
2305 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2306
Evan Chengef9e07d2006-06-15 08:11:54 +00002307 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002308
2309 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002310 break;
2311 }
Chris Lattner571d9642006-02-23 19:21:04 +00002312 case InlineAsm::isClobber: {
2313 RegsForValue ClobberedRegs =
2314 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2315 OutputRegs, InputRegs);
2316 // Add the clobbered value to the operand list, so that the register
2317 // allocator is aware that the physreg got clobbered.
2318 if (!ClobberedRegs.Regs.empty())
2319 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002320 break;
2321 }
Chris Lattner571d9642006-02-23 19:21:04 +00002322 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002323 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002324
2325 // Finish up input operands.
2326 AsmNodeOperands[0] = Chain;
2327 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2328
Chris Lattnerbd887772006-08-14 23:53:35 +00002329 Chain = DAG.getNode(ISD::INLINEASM,
2330 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002331 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002332 Flag = Chain.getValue(1);
2333
Chris Lattner2e56e892006-01-31 02:03:41 +00002334 // If this asm returns a register value, copy the result from that register
2335 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002336 if (!RetValRegs.Regs.empty())
2337 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002338
Chris Lattner2e56e892006-01-31 02:03:41 +00002339 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2340
2341 // Process indirect outputs, first output all of the flagged copies out of
2342 // physregs.
2343 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002344 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002345 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002346 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2347 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002348 }
2349
2350 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002351 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002352 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002353 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002354 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002355 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002356 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002357 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2358 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002359 DAG.setRoot(Chain);
2360}
2361
2362
Chris Lattner7a60d912005-01-07 07:47:53 +00002363void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2364 SDOperand Src = getValue(I.getOperand(0));
2365
2366 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002367
2368 if (IntPtr < Src.getValueType())
2369 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2370 else if (IntPtr > Src.getValueType())
2371 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002372
2373 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002374 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002375 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2376 Src, getIntPtrConstant(ElementSize));
2377
2378 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002379 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002380
2381 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002382 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002383 DAG.getExternalSymbol("malloc", IntPtr),
2384 Args, DAG);
2385 setValue(&I, Result.first); // Pointers always fit in registers
2386 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002387}
2388
2389void SelectionDAGLowering::visitFree(FreeInst &I) {
2390 std::vector<std::pair<SDOperand, const Type*> > Args;
2391 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002392 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002393 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002394 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002395 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002396 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2397 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002398}
2399
Chris Lattner13d7c252005-08-26 20:54:47 +00002400// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2401// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2402// instructions are special in various ways, which require special support to
2403// insert. The specified MachineInstr is created but not inserted into any
2404// basic blocks, and the scheduler passes ownership of it to this method.
2405MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2406 MachineBasicBlock *MBB) {
2407 std::cerr << "If a target marks an instruction with "
2408 "'usesCustomDAGSchedInserter', it must implement "
2409 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2410 abort();
2411 return 0;
2412}
2413
Chris Lattner58cfd792005-01-09 00:00:49 +00002414void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002415 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2416 getValue(I.getOperand(1)),
2417 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002418}
2419
2420void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002421 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2422 getValue(I.getOperand(0)),
2423 DAG.getSrcValue(I.getOperand(0)));
2424 setValue(&I, V);
2425 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002426}
2427
2428void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002429 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2430 getValue(I.getOperand(1)),
2431 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002432}
2433
2434void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002435 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2436 getValue(I.getOperand(1)),
2437 getValue(I.getOperand(2)),
2438 DAG.getSrcValue(I.getOperand(1)),
2439 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002440}
2441
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002442/// TargetLowering::LowerArguments - This is the default LowerArguments
2443/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002444/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2445/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002446std::vector<SDOperand>
2447TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2448 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2449 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002450 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002451 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2452 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2453
2454 // Add one result value for each formal argument.
2455 std::vector<MVT::ValueType> RetVals;
2456 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2457 MVT::ValueType VT = getValueType(I->getType());
2458
2459 switch (getTypeAction(VT)) {
2460 default: assert(0 && "Unknown type action!");
2461 case Legal:
2462 RetVals.push_back(VT);
2463 break;
2464 case Promote:
2465 RetVals.push_back(getTypeToTransformTo(VT));
2466 break;
2467 case Expand:
2468 if (VT != MVT::Vector) {
2469 // If this is a large integer, it needs to be broken up into small
2470 // integers. Figure out what the destination type is and how many small
2471 // integers it turns into.
2472 MVT::ValueType NVT = getTypeToTransformTo(VT);
2473 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2474 for (unsigned i = 0; i != NumVals; ++i)
2475 RetVals.push_back(NVT);
2476 } else {
2477 // Otherwise, this is a vector type. We only support legal vectors
2478 // right now.
2479 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2480 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002481
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002482 // Figure out if there is a Packed type corresponding to this Vector
2483 // type. If so, convert to the packed type.
2484 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2485 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2486 RetVals.push_back(TVT);
2487 } else {
2488 assert(0 && "Don't support illegal by-val vector arguments yet!");
2489 }
2490 }
2491 break;
2492 }
2493 }
Evan Cheng9618df12006-04-25 23:03:35 +00002494
Chris Lattner3d826992006-05-16 06:45:34 +00002495 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002496
2497 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002498 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2499 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002500 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002501
2502 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002503
2504 // Set up the return result vector.
2505 Ops.clear();
2506 unsigned i = 0;
2507 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2508 MVT::ValueType VT = getValueType(I->getType());
2509
2510 switch (getTypeAction(VT)) {
2511 default: assert(0 && "Unknown type action!");
2512 case Legal:
2513 Ops.push_back(SDOperand(Result, i++));
2514 break;
2515 case Promote: {
2516 SDOperand Op(Result, i++);
2517 if (MVT::isInteger(VT)) {
2518 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2519 : ISD::AssertZext;
2520 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2521 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2522 } else {
2523 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2524 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2525 }
2526 Ops.push_back(Op);
2527 break;
2528 }
2529 case Expand:
2530 if (VT != MVT::Vector) {
2531 // If this is a large integer, it needs to be reassembled from small
2532 // integers. Figure out what the source elt type is and how many small
2533 // integers it is.
2534 MVT::ValueType NVT = getTypeToTransformTo(VT);
2535 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2536 if (NumVals == 2) {
2537 SDOperand Lo = SDOperand(Result, i++);
2538 SDOperand Hi = SDOperand(Result, i++);
2539
2540 if (!isLittleEndian())
2541 std::swap(Lo, Hi);
2542
2543 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2544 } else {
2545 // Value scalarized into many values. Unimp for now.
2546 assert(0 && "Cannot expand i64 -> i16 yet!");
2547 }
2548 } else {
2549 // Otherwise, this is a vector type. We only support legal vectors
2550 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002551 const PackedType *PTy = cast<PackedType>(I->getType());
2552 unsigned NumElems = PTy->getNumElements();
2553 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002554
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002555 // Figure out if there is a Packed type corresponding to this Vector
2556 // type. If so, convert to the packed type.
2557 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002558 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002559 SDOperand N = SDOperand(Result, i++);
2560 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002561 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2562 DAG.getConstant(NumElems, MVT::i32),
2563 DAG.getValueType(getValueType(EltTy)));
2564 Ops.push_back(N);
2565 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002566 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002567 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002568 }
2569 }
2570 break;
2571 }
2572 }
2573 return Ops;
2574}
2575
Chris Lattneraaa23d92006-05-16 22:53:20 +00002576
2577/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2578/// implementation, which just inserts an ISD::CALL node, which is later custom
2579/// lowered by the target to something concrete. FIXME: When all targets are
2580/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2581std::pair<SDOperand, SDOperand>
2582TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2583 unsigned CallingConv, bool isTailCall,
2584 SDOperand Callee,
2585 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002586 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002587 Ops.push_back(Chain); // Op#0 - Chain
2588 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2589 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2590 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2591 Ops.push_back(Callee);
2592
2593 // Handle all of the outgoing arguments.
2594 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2595 MVT::ValueType VT = getValueType(Args[i].second);
2596 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002597 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002598 switch (getTypeAction(VT)) {
2599 default: assert(0 && "Unknown type action!");
2600 case Legal:
2601 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002602 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002603 break;
2604 case Promote:
2605 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002606 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002607 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2608 } else {
2609 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2610 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2611 }
2612 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002613 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002614 break;
2615 case Expand:
2616 if (VT != MVT::Vector) {
2617 // If this is a large integer, it needs to be broken down into small
2618 // integers. Figure out what the source elt type is and how many small
2619 // integers it is.
2620 MVT::ValueType NVT = getTypeToTransformTo(VT);
2621 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2622 if (NumVals == 2) {
2623 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2624 DAG.getConstant(0, getPointerTy()));
2625 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2626 DAG.getConstant(1, getPointerTy()));
2627 if (!isLittleEndian())
2628 std::swap(Lo, Hi);
2629
2630 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002631 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002632 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002633 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002634 } else {
2635 // Value scalarized into many values. Unimp for now.
2636 assert(0 && "Cannot expand i64 -> i16 yet!");
2637 }
2638 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002639 // Otherwise, this is a vector type. We only support legal vectors
2640 // right now.
2641 const PackedType *PTy = cast<PackedType>(Args[i].second);
2642 unsigned NumElems = PTy->getNumElements();
2643 const Type *EltTy = PTy->getElementType();
2644
2645 // Figure out if there is a Packed type corresponding to this Vector
2646 // type. If so, convert to the packed type.
2647 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002648 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2649 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2650 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2651 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002652 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002653 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002654 assert(0 && "Don't support illegal by-val vector call args yet!");
2655 abort();
2656 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002657 }
2658 break;
2659 }
2660 }
2661
2662 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002663 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002664
2665 if (RetTy != Type::VoidTy) {
2666 MVT::ValueType VT = getValueType(RetTy);
2667 switch (getTypeAction(VT)) {
2668 default: assert(0 && "Unknown type action!");
2669 case Legal:
2670 RetTys.push_back(VT);
2671 break;
2672 case Promote:
2673 RetTys.push_back(getTypeToTransformTo(VT));
2674 break;
2675 case Expand:
2676 if (VT != MVT::Vector) {
2677 // If this is a large integer, it needs to be reassembled from small
2678 // integers. Figure out what the source elt type is and how many small
2679 // integers it is.
2680 MVT::ValueType NVT = getTypeToTransformTo(VT);
2681 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2682 for (unsigned i = 0; i != NumVals; ++i)
2683 RetTys.push_back(NVT);
2684 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002685 // Otherwise, this is a vector type. We only support legal vectors
2686 // right now.
2687 const PackedType *PTy = cast<PackedType>(RetTy);
2688 unsigned NumElems = PTy->getNumElements();
2689 const Type *EltTy = PTy->getElementType();
2690
2691 // Figure out if there is a Packed type corresponding to this Vector
2692 // type. If so, convert to the packed type.
2693 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2694 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2695 RetTys.push_back(TVT);
2696 } else {
2697 assert(0 && "Don't support illegal by-val vector call results yet!");
2698 abort();
2699 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002700 }
2701 }
2702 }
2703
2704 RetTys.push_back(MVT::Other); // Always has a chain.
2705
2706 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002707 SDOperand Res = DAG.getNode(ISD::CALL,
2708 DAG.getVTList(&RetTys[0], RetTys.size()),
2709 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002710
2711 // This returns a pair of operands. The first element is the
2712 // return value for the function (if RetTy is not VoidTy). The second
2713 // element is the outgoing token chain.
2714 SDOperand ResVal;
2715 if (RetTys.size() != 1) {
2716 MVT::ValueType VT = getValueType(RetTy);
2717 if (RetTys.size() == 2) {
2718 ResVal = Res;
2719
2720 // If this value was promoted, truncate it down.
2721 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002722 if (VT == MVT::Vector) {
2723 // Insert a VBITCONVERT to convert from the packed result type to the
2724 // MVT::Vector type.
2725 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2726 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2727
2728 // Figure out if there is a Packed type corresponding to this Vector
2729 // type. If so, convert to the packed type.
2730 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2731 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002732 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2733 // "N x PTyElementVT" MVT::Vector type.
2734 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002735 DAG.getConstant(NumElems, MVT::i32),
2736 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002737 } else {
2738 abort();
2739 }
2740 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002741 unsigned AssertOp = RetTy->isSigned() ?
2742 ISD::AssertSext : ISD::AssertZext;
2743 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2744 DAG.getValueType(VT));
2745 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2746 } else {
2747 assert(MVT::isFloatingPoint(VT));
2748 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2749 }
2750 }
2751 } else if (RetTys.size() == 3) {
2752 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2753 Res.getValue(0), Res.getValue(1));
2754
2755 } else {
2756 assert(0 && "Case not handled yet!");
2757 }
2758 }
2759
2760 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2761}
2762
2763
2764
Chris Lattner58cfd792005-01-09 00:00:49 +00002765// It is always conservatively correct for llvm.returnaddress and
2766// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002767//
2768// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2769// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002770std::pair<SDOperand, SDOperand>
2771TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2772 unsigned Depth, SelectionDAG &DAG) {
2773 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002774}
2775
Chris Lattner29dcc712005-05-14 05:50:48 +00002776SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002777 assert(0 && "LowerOperation not implemented for this target!");
2778 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002779 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002780}
2781
Nate Begeman595ec732006-01-28 03:14:31 +00002782SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2783 SelectionDAG &DAG) {
2784 assert(0 && "CustomPromoteOperation not implemented for this target!");
2785 abort();
2786 return SDOperand();
2787}
2788
Chris Lattner58cfd792005-01-09 00:00:49 +00002789void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002790 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00002791 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002792 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002793 setValue(&I, Result.first);
2794 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002795}
2796
Evan Cheng6781b6e2006-02-15 21:59:04 +00002797/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002798/// operand.
2799static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002800 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002801 MVT::ValueType CurVT = VT;
2802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2803 uint64_t Val = C->getValue() & 255;
2804 unsigned Shift = 8;
2805 while (CurVT != MVT::i8) {
2806 Val = (Val << Shift) | Val;
2807 Shift <<= 1;
2808 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002809 }
2810 return DAG.getConstant(Val, VT);
2811 } else {
2812 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2813 unsigned Shift = 8;
2814 while (CurVT != MVT::i8) {
2815 Value =
2816 DAG.getNode(ISD::OR, VT,
2817 DAG.getNode(ISD::SHL, VT, Value,
2818 DAG.getConstant(Shift, MVT::i8)), Value);
2819 Shift <<= 1;
2820 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002821 }
2822
2823 return Value;
2824 }
2825}
2826
Evan Cheng6781b6e2006-02-15 21:59:04 +00002827/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2828/// used when a memcpy is turned into a memset when the source is a constant
2829/// string ptr.
2830static SDOperand getMemsetStringVal(MVT::ValueType VT,
2831 SelectionDAG &DAG, TargetLowering &TLI,
2832 std::string &Str, unsigned Offset) {
2833 MVT::ValueType CurVT = VT;
2834 uint64_t Val = 0;
2835 unsigned MSB = getSizeInBits(VT) / 8;
2836 if (TLI.isLittleEndian())
2837 Offset = Offset + MSB - 1;
2838 for (unsigned i = 0; i != MSB; ++i) {
2839 Val = (Val << 8) | Str[Offset];
2840 Offset += TLI.isLittleEndian() ? -1 : 1;
2841 }
2842 return DAG.getConstant(Val, VT);
2843}
2844
Evan Cheng81fcea82006-02-14 08:22:34 +00002845/// getMemBasePlusOffset - Returns base and offset node for the
2846static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2847 SelectionDAG &DAG, TargetLowering &TLI) {
2848 MVT::ValueType VT = Base.getValueType();
2849 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2850}
2851
Evan Chengdb2a7a72006-02-14 20:12:38 +00002852/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002853/// to replace the memset / memcpy is below the threshold. It also returns the
2854/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002855static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2856 unsigned Limit, uint64_t Size,
2857 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002858 MVT::ValueType VT;
2859
2860 if (TLI.allowsUnalignedMemoryAccesses()) {
2861 VT = MVT::i64;
2862 } else {
2863 switch (Align & 7) {
2864 case 0:
2865 VT = MVT::i64;
2866 break;
2867 case 4:
2868 VT = MVT::i32;
2869 break;
2870 case 2:
2871 VT = MVT::i16;
2872 break;
2873 default:
2874 VT = MVT::i8;
2875 break;
2876 }
2877 }
2878
Evan Chengd5026102006-02-14 09:11:59 +00002879 MVT::ValueType LVT = MVT::i64;
2880 while (!TLI.isTypeLegal(LVT))
2881 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2882 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002883
Evan Chengd5026102006-02-14 09:11:59 +00002884 if (VT > LVT)
2885 VT = LVT;
2886
Evan Cheng04514992006-02-14 23:05:54 +00002887 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002888 while (Size != 0) {
2889 unsigned VTSize = getSizeInBits(VT) / 8;
2890 while (VTSize > Size) {
2891 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002892 VTSize >>= 1;
2893 }
Evan Chengd5026102006-02-14 09:11:59 +00002894 assert(MVT::isInteger(VT));
2895
2896 if (++NumMemOps > Limit)
2897 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002898 MemOps.push_back(VT);
2899 Size -= VTSize;
2900 }
Evan Chengd5026102006-02-14 09:11:59 +00002901
2902 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002903}
2904
Chris Lattner875def92005-01-11 05:56:49 +00002905void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002906 SDOperand Op1 = getValue(I.getOperand(1));
2907 SDOperand Op2 = getValue(I.getOperand(2));
2908 SDOperand Op3 = getValue(I.getOperand(3));
2909 SDOperand Op4 = getValue(I.getOperand(4));
2910 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2911 if (Align == 0) Align = 1;
2912
2913 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2914 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002915
2916 // Expand memset / memcpy to a series of load / store ops
2917 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002918 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00002919 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002920 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002921 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002922 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2923 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002924 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002925 unsigned Offset = 0;
2926 for (unsigned i = 0; i < NumMemOps; i++) {
2927 MVT::ValueType VT = MemOps[i];
2928 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002929 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00002930 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002931 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002932 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00002933 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002934 Offset += VTSize;
2935 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002936 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002937 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002938 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002939 case ISD::MEMCPY: {
2940 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2941 Size->getValue(), Align, TLI)) {
2942 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002943 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002944 GlobalAddressSDNode *G = NULL;
2945 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002946 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002947
2948 if (Op2.getOpcode() == ISD::GlobalAddress)
2949 G = cast<GlobalAddressSDNode>(Op2);
2950 else if (Op2.getOpcode() == ISD::ADD &&
2951 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2952 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2953 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002954 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002955 }
2956 if (G) {
2957 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002958 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002959 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002960 if (!Str.empty()) {
2961 CopyFromStr = true;
2962 SrcOff += SrcDelta;
2963 }
2964 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002965 }
2966
Evan Chenge2038bd2006-02-15 01:54:51 +00002967 for (unsigned i = 0; i < NumMemOps; i++) {
2968 MVT::ValueType VT = MemOps[i];
2969 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002970 SDOperand Value, Chain, Store;
2971
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002972 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002973 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2974 Chain = getRoot();
2975 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002976 DAG.getStore(Chain, Value,
2977 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002978 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002979 } else {
2980 Value = DAG.getLoad(VT, getRoot(),
2981 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00002982 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002983 Chain = Value.getValue(1);
2984 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002985 DAG.getStore(Chain, Value,
2986 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002987 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002988 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002989 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002990 SrcOff += VTSize;
2991 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002992 }
2993 }
2994 break;
2995 }
2996 }
2997
2998 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002999 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3000 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003001 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003002 }
3003 }
3004
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003005 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003006}
3007
Chris Lattner875def92005-01-11 05:56:49 +00003008//===----------------------------------------------------------------------===//
3009// SelectionDAGISel code
3010//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003011
3012unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3013 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3014}
3015
Chris Lattnerc9950c12005-08-17 06:37:43 +00003016void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003017 // FIXME: we only modify the CFG to split critical edges. This
3018 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003019 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003020}
Chris Lattner7a60d912005-01-07 07:47:53 +00003021
Chris Lattner35397782005-12-05 07:10:48 +00003022
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003023/// OptimizeNoopCopyExpression - We have determined that the specified cast
3024/// instruction is a noop copy (e.g. it's casting from one pointer type to
3025/// another, int->uint, or int->sbyte on PPC.
3026///
3027/// Return true if any changes are made.
3028static bool OptimizeNoopCopyExpression(CastInst *CI) {
3029 BasicBlock *DefBB = CI->getParent();
3030
3031 /// InsertedCasts - Only insert a cast in each block once.
3032 std::map<BasicBlock*, CastInst*> InsertedCasts;
3033
3034 bool MadeChange = false;
3035 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3036 UI != E; ) {
3037 Use &TheUse = UI.getUse();
3038 Instruction *User = cast<Instruction>(*UI);
3039
3040 // Figure out which BB this cast is used in. For PHI's this is the
3041 // appropriate predecessor block.
3042 BasicBlock *UserBB = User->getParent();
3043 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3044 unsigned OpVal = UI.getOperandNo()/2;
3045 UserBB = PN->getIncomingBlock(OpVal);
3046 }
3047
3048 // Preincrement use iterator so we don't invalidate it.
3049 ++UI;
3050
3051 // If this user is in the same block as the cast, don't change the cast.
3052 if (UserBB == DefBB) continue;
3053
3054 // If we have already inserted a cast into this block, use it.
3055 CastInst *&InsertedCast = InsertedCasts[UserBB];
3056
3057 if (!InsertedCast) {
3058 BasicBlock::iterator InsertPt = UserBB->begin();
3059 while (isa<PHINode>(InsertPt)) ++InsertPt;
3060
3061 InsertedCast =
3062 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3063 MadeChange = true;
3064 }
3065
3066 // Replace a use of the cast with a use of the new casat.
3067 TheUse = InsertedCast;
3068 }
3069
3070 // If we removed all uses, nuke the cast.
3071 if (CI->use_empty())
3072 CI->eraseFromParent();
3073
3074 return MadeChange;
3075}
3076
Chris Lattner35397782005-12-05 07:10:48 +00003077/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3078/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003079static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3080 Instruction *GEPI, Value *Ptr,
3081 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003082 if (V) return V; // Already computed.
3083
3084 BasicBlock::iterator InsertPt;
3085 if (BB == GEPI->getParent()) {
3086 // If insert into the GEP's block, insert right after the GEP.
3087 InsertPt = GEPI;
3088 ++InsertPt;
3089 } else {
3090 // Otherwise, insert at the top of BB, after any PHI nodes
3091 InsertPt = BB->begin();
3092 while (isa<PHINode>(InsertPt)) ++InsertPt;
3093 }
3094
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003095 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3096 // BB so that there is only one value live across basic blocks (the cast
3097 // operand).
3098 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3099 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3100 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3101
Chris Lattner35397782005-12-05 07:10:48 +00003102 // Add the offset, cast it to the right type.
3103 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003104 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003105}
3106
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003107/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3108/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3109/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3110/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3111/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3112/// the constant add into a load or store instruction. Additionally, if a user
3113/// is a pointer-pointer cast, we look through it to find its users.
3114static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3115 Constant *PtrOffset, BasicBlock *DefBB,
3116 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003117 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003118 while (!RepPtr->use_empty()) {
3119 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003120
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003121 // If the user is a Pointer-Pointer cast, recurse.
3122 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3123 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003124
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003125 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3126 // could invalidate an iterator.
3127 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3128 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003129 }
3130
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003131 // If this is a load of the pointer, or a store through the pointer, emit
3132 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003133 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003134 if (isa<LoadInst>(User) ||
3135 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3136 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3137 User->getParent(), GEPI,
3138 Ptr, PtrOffset);
3139 } else {
3140 // If this use is not foldable into the addressing mode, use a version
3141 // emitted in the GEP block.
3142 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3143 Ptr, PtrOffset);
3144 }
3145
Chris Lattner21cd9902006-05-06 09:10:37 +00003146 if (GEPI->getType() != RepPtr->getType()) {
3147 BasicBlock::iterator IP = NewVal;
3148 ++IP;
3149 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3150 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003151 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003152 }
3153}
Chris Lattner35397782005-12-05 07:10:48 +00003154
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003155
Chris Lattner35397782005-12-05 07:10:48 +00003156/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3157/// selection, we want to be a bit careful about some things. In particular, if
3158/// we have a GEP instruction that is used in a different block than it is
3159/// defined, the addressing expression of the GEP cannot be folded into loads or
3160/// stores that use it. In this case, decompose the GEP and move constant
3161/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003162static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003163 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003164 // If this GEP is only used inside the block it is defined in, there is no
3165 // need to rewrite it.
3166 bool isUsedOutsideDefBB = false;
3167 BasicBlock *DefBB = GEPI->getParent();
3168 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3169 UI != E; ++UI) {
3170 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3171 isUsedOutsideDefBB = true;
3172 break;
3173 }
3174 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003175 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003176
3177 // If this GEP has no non-zero constant indices, there is nothing we can do,
3178 // ignore it.
3179 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003180 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003181 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3182 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003183 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003184 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003185 hasConstantIndex = true;
3186 break;
3187 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003188 } else {
3189 hasVariableIndex = true;
3190 }
Chris Lattner35397782005-12-05 07:10:48 +00003191 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003192
3193 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3194 if (!hasConstantIndex && !hasVariableIndex) {
3195 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3196 GEPI->getName(), GEPI);
3197 GEPI->replaceAllUsesWith(NC);
3198 GEPI->eraseFromParent();
3199 return true;
3200 }
3201
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003202 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003203 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3204 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003205
3206 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3207 // constant offset (which we now know is non-zero) and deal with it later.
3208 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003209 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003210 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3211 const Type *Ty = GEPI->getOperand(0)->getType();
3212
3213 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3214 E = GEPI->op_end(); OI != E; ++OI) {
3215 Value *Idx = *OI;
3216 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003217 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003218 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003219 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003220 Ty = StTy->getElementType(Field);
3221 } else {
3222 Ty = cast<SequentialType>(Ty)->getElementType();
3223
3224 // Handle constant subscripts.
3225 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003226 if (CI->getZExtValue() == 0) continue;
3227 if (CI->getType()->isSigned())
3228 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003229 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003230 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003231 continue;
3232 }
3233
3234 // Ptr = Ptr + Idx * ElementSize;
3235
3236 // Cast Idx to UIntPtrTy if needed.
3237 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3238
Owen Anderson20a631f2006-05-03 01:29:57 +00003239 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003240 // Mask off bits that should not be set.
3241 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003242 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003243
3244 // Multiply by the element size and add to the base.
3245 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3246 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3247 }
3248 }
3249
3250 // Make sure that the offset fits in uintptr_t.
3251 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003252 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003253
3254 // Okay, we have now emitted all of the variable index parts to the BB that
3255 // the GEP is defined in. Loop over all of the using instructions, inserting
3256 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003257 // instruction to use the newly computed value, making GEPI dead. When the
3258 // user is a load or store instruction address, we emit the add into the user
3259 // block, otherwise we use a canonical version right next to the gep (these
3260 // won't be foldable as addresses, so we might as well share the computation).
3261
Chris Lattner21cd9902006-05-06 09:10:37 +00003262 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003263 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003264
3265 // Finally, the GEP is dead, remove it.
3266 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003267
3268 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003269}
3270
Chris Lattnera9caf952006-09-28 06:17:10 +00003271/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3272/// constant operands, and if any of the edges feeding the PHI node are
3273/// critical, split them so that the assignments of a constant to a register
3274/// will not be executed on a path that isn't relevant.
3275void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003276 // The most common case is that this is a PHI node with two incoming
3277 // successors handle this case efficiently, because it is simple.
3278 PHINode *PN = cast<PHINode>(BB->begin());
3279 if (PN->getNumIncomingValues() == 2) {
3280 // If neither edge is critical, we never need to split.
3281 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3282 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3283 return;
3284
3285 BasicBlock::iterator BBI = BB->begin();
3286 while ((PN = dyn_cast<PHINode>(BBI++))) {
3287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3288 if (isa<Constant>(PN->getIncomingValue(i)))
3289 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3290 }
3291 return;
3292 }
3293
3294 // Otherwise, things are a bit trickier.
3295
3296 // BE SMART HERE.
3297
Chris Lattnera9caf952006-09-28 06:17:10 +00003298 BasicBlock::iterator BBI = BB->begin();
3299 while ((PN = dyn_cast<PHINode>(BBI++))) {
3300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3301 if (isa<Constant>(PN->getIncomingValue(i)))
3302 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3303 }
3304}
3305
3306
Chris Lattner7a60d912005-01-07 07:47:53 +00003307bool SelectionDAGISel::runOnFunction(Function &Fn) {
3308 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3309 RegMap = MF.getSSARegMap();
3310 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3311
Chris Lattner35397782005-12-05 07:10:48 +00003312 // First, split all critical edges for PHI nodes with incoming values that are
3313 // constants, this way the load of the constant into a vreg will not be placed
3314 // into MBBs that are used some other way.
3315 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003316 // In this pass we also look for GEP and cast instructions that are used
3317 // across basic blocks and rewrite them to improve basic-block-at-a-time
3318 // selection.
3319 //
Chris Lattner35397782005-12-05 07:10:48 +00003320 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003321 bool MadeChange = true;
3322 while (MadeChange) {
3323 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003324 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003325 // If this block has any PHI nodes with constant operands, and if any of the
3326 // edges feeding the PHI node are critical, split them.
3327 if (isa<PHINode>(BB->begin()))
3328 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003329
Chris Lattnera9caf952006-09-28 06:17:10 +00003330 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003331 Instruction *I = BBI++;
3332 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003333 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003334 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003335 // If the source of the cast is a constant, then this should have
3336 // already been constant folded. The only reason NOT to constant fold
3337 // it is if something (e.g. LSR) was careful to place the constant
3338 // evaluation in a block other than then one that uses it (e.g. to hoist
3339 // the address of globals out of a loop). If this is the case, we don't
3340 // want to forward-subst the cast.
3341 if (isa<Constant>(CI->getOperand(0)))
3342 continue;
3343
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003344 // If this is a noop copy, sink it into user blocks to reduce the number
3345 // of virtual registers that must be created and coallesced.
3346 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3347 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3348
3349 // This is an fp<->int conversion?
3350 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3351 continue;
3352
3353 // If this is an extension, it will be a zero or sign extension, which
3354 // isn't a noop.
3355 if (SrcVT < DstVT) continue;
3356
3357 // If these values will be promoted, find out what they will be promoted
3358 // to. This helps us consider truncates on PPC as noop copies when they
3359 // are.
3360 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3361 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3362 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3363 DstVT = TLI.getTypeToTransformTo(DstVT);
3364
3365 // If, after promotion, these are the same types, this is a noop copy.
3366 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003367 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003368 }
3369 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003370 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003371 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003372
Chris Lattner7a60d912005-01-07 07:47:53 +00003373 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3374
3375 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3376 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003377
Chris Lattner7a60d912005-01-07 07:47:53 +00003378 return true;
3379}
3380
3381
Chris Lattner718b5c22005-01-13 17:59:43 +00003382SDOperand SelectionDAGISel::
3383CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00003384 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003385 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003386 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003387 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003388
3389 // If this type is not legal, we must make sure to not create an invalid
3390 // register use.
3391 MVT::ValueType SrcVT = Op.getValueType();
3392 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3393 SelectionDAG &DAG = SDL.DAG;
3394 if (SrcVT == DestVT) {
3395 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003396 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003397 // Handle copies from generic vectors to registers.
3398 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3399 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3400 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003401
Chris Lattner5fe1f542006-03-31 02:06:56 +00003402 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3403 // MVT::Vector type.
3404 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3405 DAG.getConstant(NE, MVT::i32),
3406 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003407
Chris Lattner5fe1f542006-03-31 02:06:56 +00003408 // Loop over all of the elements of the resultant vector,
3409 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3410 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003411 SmallVector<SDOperand, 8> OutChains;
Chris Lattner5fe1f542006-03-31 02:06:56 +00003412 SDOperand Root = SDL.getRoot();
3413 for (unsigned i = 0; i != NE; ++i) {
3414 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003415 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003416 if (PTyElementVT == PTyLegalElementVT) {
3417 // Elements are legal.
3418 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3419 } else if (PTyLegalElementVT > PTyElementVT) {
3420 // Elements are promoted.
3421 if (MVT::isFloatingPoint(PTyLegalElementVT))
3422 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3423 else
3424 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3425 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3426 } else {
3427 // Elements are expanded.
3428 // The src value is expanded into multiple registers.
3429 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003430 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003431 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003432 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003433 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3434 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3435 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003436 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003437 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3438 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003439 } else if (SrcVT < DestVT) {
3440 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003441 if (MVT::isFloatingPoint(SrcVT))
3442 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3443 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003444 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003445 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3446 } else {
3447 // The src value is expanded into multiple registers.
3448 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003449 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003450 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003451 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003452 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3453 return DAG.getCopyToReg(Op, Reg+1, Hi);
3454 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003455}
3456
Chris Lattner16f64df2005-01-17 17:15:02 +00003457void SelectionDAGISel::
3458LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3459 std::vector<SDOperand> &UnorderedChains) {
3460 // If this is the entry block, emit arguments.
3461 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003462 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003463 SDOperand OldRoot = SDL.DAG.getRoot();
3464 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003465
Chris Lattner6871b232005-10-30 19:42:35 +00003466 unsigned a = 0;
3467 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3468 AI != E; ++AI, ++a)
3469 if (!AI->use_empty()) {
3470 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003471
Chris Lattner6871b232005-10-30 19:42:35 +00003472 // If this argument is live outside of the entry block, insert a copy from
3473 // whereever we got it to the vreg that other BB's will reference it as.
3474 if (FuncInfo.ValueMap.count(AI)) {
3475 SDOperand Copy =
3476 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3477 UnorderedChains.push_back(Copy);
3478 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003479 }
Chris Lattner6871b232005-10-30 19:42:35 +00003480
Chris Lattner6871b232005-10-30 19:42:35 +00003481 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003482 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003483 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003484}
3485
Chris Lattner7a60d912005-01-07 07:47:53 +00003486void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3487 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003488 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003489 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003490
3491 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003492
Chris Lattner6871b232005-10-30 19:42:35 +00003493 // Lower any arguments needed in this block if this is the entry block.
3494 if (LLVMBB == &LLVMBB->getParent()->front())
3495 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003496
3497 BB = FuncInfo.MBBMap[LLVMBB];
3498 SDL.setCurrentBasicBlock(BB);
3499
3500 // Lower all of the non-terminator instructions.
3501 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3502 I != E; ++I)
3503 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003504
Chris Lattner7a60d912005-01-07 07:47:53 +00003505 // Ensure that all instructions which are used outside of their defining
3506 // blocks are available as virtual registers.
3507 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003508 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003509 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003510 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003511 UnorderedChains.push_back(
3512 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003513 }
3514
3515 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3516 // ensure constants are generated when needed. Remember the virtual registers
3517 // that need to be added to the Machine PHI nodes as input. We cannot just
3518 // directly add them, because expansion might result in multiple MBB's for one
3519 // BB. As such, the start of the BB might correspond to a different MBB than
3520 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003521 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003522
3523 // Emit constants only once even if used by multiple PHI nodes.
3524 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003525
Chris Lattner7a60d912005-01-07 07:47:53 +00003526 // Check successor nodes PHI nodes that expect a constant to be available from
3527 // this block.
3528 TerminatorInst *TI = LLVMBB->getTerminator();
3529 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3530 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003531 if (!isa<PHINode>(SuccBB->begin())) continue;
3532
Chris Lattner7a60d912005-01-07 07:47:53 +00003533 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3534 PHINode *PN;
3535
3536 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3537 // nodes and Machine PHI nodes, but the incoming operands have not been
3538 // emitted yet.
3539 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003540 (PN = dyn_cast<PHINode>(I)); ++I)
3541 if (!PN->use_empty()) {
3542 unsigned Reg;
3543 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3544 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3545 unsigned &RegOut = ConstantsOut[C];
3546 if (RegOut == 0) {
3547 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003548 UnorderedChains.push_back(
3549 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003550 }
3551 Reg = RegOut;
3552 } else {
3553 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003554 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003555 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003556 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3557 "Didn't codegen value into a register!??");
3558 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003559 UnorderedChains.push_back(
3560 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003561 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003562 }
Misha Brukman835702a2005-04-21 22:36:52 +00003563
Chris Lattner8ea875f2005-01-07 21:34:19 +00003564 // Remember that this register needs to added to the machine PHI node as
3565 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003566 MVT::ValueType VT = TLI.getValueType(PN->getType());
3567 unsigned NumElements;
3568 if (VT != MVT::Vector)
3569 NumElements = TLI.getNumElements(VT);
3570 else {
3571 MVT::ValueType VT1,VT2;
3572 NumElements =
3573 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3574 VT1, VT2);
3575 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003576 for (unsigned i = 0, e = NumElements; i != e; ++i)
3577 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003578 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003579 }
3580 ConstantsOut.clear();
3581
Chris Lattner718b5c22005-01-13 17:59:43 +00003582 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003583 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003584 SDOperand Root = SDL.getRoot();
3585 if (Root.getOpcode() != ISD::EntryToken) {
3586 unsigned i = 0, e = UnorderedChains.size();
3587 for (; i != e; ++i) {
3588 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3589 if (UnorderedChains[i].Val->getOperand(0) == Root)
3590 break; // Don't add the root if we already indirectly depend on it.
3591 }
3592
3593 if (i == e)
3594 UnorderedChains.push_back(Root);
3595 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003596 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3597 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003598 }
3599
Chris Lattner7a60d912005-01-07 07:47:53 +00003600 // Lower the terminator after the copies are emitted.
3601 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003602
Nate Begemaned728c12006-03-27 01:32:24 +00003603 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003604 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003605 SwitchCases.clear();
3606 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003607 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003608
Chris Lattner4108bb02005-01-17 19:43:36 +00003609 // Make sure the root of the DAG is up-to-date.
3610 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003611}
3612
Nate Begemaned728c12006-03-27 01:32:24 +00003613void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003614 // Get alias analysis for load/store combining.
3615 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3616
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003617 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003618 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003619
Chris Lattner7a60d912005-01-07 07:47:53 +00003620 DEBUG(std::cerr << "Lowered selection DAG:\n");
3621 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003622
Chris Lattner7a60d912005-01-07 07:47:53 +00003623 // Second step, hack on the DAG until it only uses operations and types that
3624 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003625 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003626
Chris Lattner7a60d912005-01-07 07:47:53 +00003627 DEBUG(std::cerr << "Legalized selection DAG:\n");
3628 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003629
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003630 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003631 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003632
Evan Cheng739a6a42006-01-21 02:32:06 +00003633 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003634
Chris Lattner5ca31d92005-03-30 01:10:47 +00003635 // Third, instruction select all of the operations to machine code, adding the
3636 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003637 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003638
Chris Lattner7a60d912005-01-07 07:47:53 +00003639 DEBUG(std::cerr << "Selected machine code:\n");
3640 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003641}
Chris Lattner7a60d912005-01-07 07:47:53 +00003642
Nate Begemaned728c12006-03-27 01:32:24 +00003643void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3644 FunctionLoweringInfo &FuncInfo) {
3645 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3646 {
3647 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3648 CurDAG = &DAG;
3649
3650 // First step, lower LLVM code to some DAG. This DAG may use operations and
3651 // types that are not supported by the target.
3652 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3653
3654 // Second step, emit the lowered DAG as machine code.
3655 CodeGenAndEmitDAG(DAG);
3656 }
3657
Chris Lattner5ca31d92005-03-30 01:10:47 +00003658 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003659 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003660 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003661 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3662 MachineInstr *PHI = PHINodesToUpdate[i].first;
3663 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3664 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003665 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003666 PHI->addMachineBasicBlockOperand(BB);
3667 }
3668 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003669 }
Nate Begemaned728c12006-03-27 01:32:24 +00003670
Nate Begeman866b4b42006-04-23 06:26:20 +00003671 // If the JumpTable record is filled in, then we need to emit a jump table.
3672 // Updating the PHI nodes is tricky in this case, since we need to determine
3673 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003674 if (JT.Reg) {
3675 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3676 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3677 CurDAG = &SDAG;
3678 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003679 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003680 // Set the current basic block to the mbb we wish to insert the code into
3681 BB = JT.MBB;
3682 SDL.setCurrentBasicBlock(BB);
3683 // Emit the code
3684 SDL.visitJumpTable(JT);
3685 SDAG.setRoot(SDL.getRoot());
3686 CodeGenAndEmitDAG(SDAG);
3687 // Update PHI Nodes
3688 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3689 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3690 MachineBasicBlock *PHIBB = PHI->getParent();
3691 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3692 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003693 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003694 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003695 PHI->addMachineBasicBlockOperand(RangeBB);
3696 }
3697 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003698 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003699 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003700 }
3701 }
3702 return;
3703 }
3704
Chris Lattner76a7bc82006-10-22 23:00:53 +00003705 // If the switch block involved a branch to one of the actual successors, we
3706 // need to update PHI nodes in that block.
3707 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3708 MachineInstr *PHI = PHINodesToUpdate[i].first;
3709 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3710 "This is not a machine PHI node that we are updating!");
3711 if (BB->isSuccessor(PHI->getParent())) {
3712 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3713 PHI->addMachineBasicBlockOperand(BB);
3714 }
3715 }
3716
Nate Begemaned728c12006-03-27 01:32:24 +00003717 // If we generated any switch lowering information, build and codegen any
3718 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003719 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003720 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3721 CurDAG = &SDAG;
3722 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003723
Nate Begemaned728c12006-03-27 01:32:24 +00003724 // Set the current basic block to the mbb we wish to insert the code into
3725 BB = SwitchCases[i].ThisBB;
3726 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003727
Nate Begemaned728c12006-03-27 01:32:24 +00003728 // Emit the code
3729 SDL.visitSwitchCase(SwitchCases[i]);
3730 SDAG.setRoot(SDL.getRoot());
3731 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003732
3733 // Handle any PHI nodes in successors of this chunk, as if we were coming
3734 // from the original BB before switch expansion. Note that PHI nodes can
3735 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3736 // handle them the right number of times.
3737 while ((BB = SwitchCases[i].LHSBB)) { // Handle LHS and RHS.
3738 for (MachineBasicBlock::iterator Phi = BB->begin();
3739 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3740 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3741 for (unsigned pn = 0; ; ++pn) {
3742 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3743 if (PHINodesToUpdate[pn].first == Phi) {
3744 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3745 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3746 break;
3747 }
3748 }
Nate Begemaned728c12006-03-27 01:32:24 +00003749 }
Chris Lattner707339a52006-09-07 01:59:34 +00003750
3751 // Don't process RHS if same block as LHS.
3752 if (BB == SwitchCases[i].RHSBB)
3753 SwitchCases[i].RHSBB = 0;
3754
3755 // If we haven't handled the RHS, do so now. Otherwise, we're done.
3756 SwitchCases[i].LHSBB = SwitchCases[i].RHSBB;
3757 SwitchCases[i].RHSBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003758 }
Chris Lattner707339a52006-09-07 01:59:34 +00003759 assert(SwitchCases[i].LHSBB == 0 && SwitchCases[i].RHSBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003760 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003761}
Evan Cheng739a6a42006-01-21 02:32:06 +00003762
Jim Laskey95eda5b2006-08-01 14:21:23 +00003763
Evan Cheng739a6a42006-01-21 02:32:06 +00003764//===----------------------------------------------------------------------===//
3765/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3766/// target node in the graph.
3767void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3768 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003769
Jim Laskey29e635d2006-08-02 12:30:23 +00003770 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003771
3772 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003773 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003774 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003775 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003776
Jim Laskey03593f72006-08-01 18:29:48 +00003777 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003778 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003779 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003780}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003781
Chris Lattner47639db2006-03-06 00:22:00 +00003782
Jim Laskey03593f72006-08-01 18:29:48 +00003783HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3784 return new HazardRecognizer();
3785}
3786
Chris Lattner6df34962006-10-11 03:58:02 +00003787//===----------------------------------------------------------------------===//
3788// Helper functions used by the generated instruction selector.
3789//===----------------------------------------------------------------------===//
3790// Calls to these methods are generated by tblgen.
3791
3792/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3793/// the dag combiner simplified the 255, we still want to match. RHS is the
3794/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3795/// specified in the .td file (e.g. 255).
3796bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3797 int64_t DesiredMaskS) {
3798 uint64_t ActualMask = RHS->getValue();
3799 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3800
3801 // If the actual mask exactly matches, success!
3802 if (ActualMask == DesiredMask)
3803 return true;
3804
3805 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3806 if (ActualMask & ~DesiredMask)
3807 return false;
3808
3809 // Otherwise, the DAG Combiner may have proven that the value coming in is
3810 // either already zero or is not demanded. Check for known zero input bits.
3811 uint64_t NeededMask = DesiredMask & ~ActualMask;
3812 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3813 return true;
3814
3815 // TODO: check to see if missing bits are just not demanded.
3816
3817 // Otherwise, this pattern doesn't match.
3818 return false;
3819}
3820
3821/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3822/// the dag combiner simplified the 255, we still want to match. RHS is the
3823/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3824/// specified in the .td file (e.g. 255).
3825bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3826 int64_t DesiredMaskS) {
3827 uint64_t ActualMask = RHS->getValue();
3828 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3829
3830 // If the actual mask exactly matches, success!
3831 if (ActualMask == DesiredMask)
3832 return true;
3833
3834 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3835 if (ActualMask & ~DesiredMask)
3836 return false;
3837
3838 // Otherwise, the DAG Combiner may have proven that the value coming in is
3839 // either already zero or is not demanded. Check for known zero input bits.
3840 uint64_t NeededMask = DesiredMask & ~ActualMask;
3841
3842 uint64_t KnownZero, KnownOne;
3843 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
3844
3845 // If all the missing bits in the or are already known to be set, match!
3846 if ((NeededMask & KnownOne) == NeededMask)
3847 return true;
3848
3849 // TODO: check to see if missing bits are just not demanded.
3850
3851 // Otherwise, this pattern doesn't match.
3852 return false;
3853}
3854
Jim Laskey03593f72006-08-01 18:29:48 +00003855
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003856/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3857/// by tblgen. Others should not call it.
3858void SelectionDAGISel::
3859SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3860 std::vector<SDOperand> InOps;
3861 std::swap(InOps, Ops);
3862
3863 Ops.push_back(InOps[0]); // input chain.
3864 Ops.push_back(InOps[1]); // input asm string.
3865
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003866 unsigned i = 2, e = InOps.size();
3867 if (InOps[e-1].getValueType() == MVT::Flag)
3868 --e; // Don't process a flag operand if it is here.
3869
3870 while (i != e) {
3871 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3872 if ((Flags & 7) != 4 /*MEM*/) {
3873 // Just skip over this operand, copying the operands verbatim.
3874 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3875 i += (Flags >> 3) + 1;
3876 } else {
3877 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3878 // Otherwise, this is a memory operand. Ask the target to select it.
3879 std::vector<SDOperand> SelOps;
3880 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3881 std::cerr << "Could not match memory address. Inline asm failure!\n";
3882 exit(1);
3883 }
3884
3885 // Add this to the output node.
3886 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3887 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3888 i += 2;
3889 }
3890 }
3891
3892 // Add the flag input back if present.
3893 if (e != InOps.size())
3894 Ops.push_back(InOps.back());
3895}